6

i have an Integer value:

Integer value = 56472201;

Where the value could be positive or negative.

When I divide the value by 1000000, I want this result in the form 56.472201 but instead it gives me just the quotient. How am I able to get both the quotient and remainder values?

Femaref
  • 60,705
  • 7
  • 138
  • 176
jimmy
  • 8,121
  • 11
  • 36
  • 40

3 Answers3

6

cast it to float and then do it:

int i = 56472201;

float j = ((float) i)/1000000.0

Edit: Due to precision(needed in your case), use double. Also as pointed by Konrad Rudolph, no need for explicit casting:

double j = i / 1000000.0;
lalli
  • 6,083
  • 7
  • 42
  • 55
1

You have to convert the value to a floating point type first, otherwise you will be doing an integer division.

Example in C#:

int value = 56472201;
double decimalValue = (double)value / 1000000.0;

(The cast is actually not needed in this code, as dividing by a floating point number will cast the value to match, but it's clearer to write out the cast in the code as that is what actually happens.)

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

If you divide an int by a double you will be left with a double result as illustrated by this unit test.

@Test
public void testIntToDouble() throws Exception {
    final int x = 56472201;
    Assert.assertEquals(56.472201, x / 1e6d);
}

1e6d is 1 * 10^6 represented as a double

Jon Freedman
  • 9,469
  • 4
  • 39
  • 58