0

How do I get the integer portion and the remainder of the number? For example, I have a number of float type, 123.456789, and I want to copy the integer portion of the number into an int variable and the remainder of the number into a float in :

float a = 123.456789
int b = 123
float c = 0.456789
jxh
  • 69,070
  • 8
  • 110
  • 193
Motti
  • 3
  • 2

2 Answers2

4

You could do the following:

float a = 123.456789f;
int b = (int)a; //Remove the remainder by casting to `int`
float c = a - b;
Marv
  • 3,517
  • 2
  • 22
  • 47
0

The "overkill" solution:

float a = 123.456789f;
int b = (int) Math.floor(a);
float c = a - b;
Barranka
  • 20,547
  • 13
  • 65
  • 83
  • Why use `floor()` though? Casting to int will always round down. – Marv Jun 30 '15 at 16:40
  • @Marv That's why I said this was the "overkill" solution... you've already posted the simple, casting, solution... I just put this to illustrate that there are indeed many ways to do the same thing (some more efficient and clean than others) – Barranka Jun 30 '15 at 16:41
  • 1
    @Marv - casting and `Math.floor` give different results for negative, non-integral numbers. OP didn't specify the desired behavior for negative numbers, however, so it's hard to say which approach is preferred here. – Ted Hopp Jun 30 '15 at 17:28
  • 1
    @TedHopp I would've thought the OP would want `-123.0` and `-0.456789` for `-123.456789` but you're right, we can't say for sure. – Marv Jul 01 '15 at 10:59