How can I convert an integer value to a decimal value?

i is Integer:

Integer value = 56472201; 

If the value can be positive or negative.

When I divide the value by 1,000,000, I want to get this result in the form 56.472201 , but instead it gives me only the quotient. How can I get the values โ€‹โ€‹of both private and residual?

+6
java integer-division
source share
3 answers

release it so that it swims, and then do the following:

 int i = 56472201; float j = ((float) i)/1000000.0 

Edit: due to accuracy (necessary in your case) use double. Also, as Conrad Rudolph pointed out, there is no need for explicit casting:

 double j = i / 1000000.0; 
+6
source share

If you divide the int into double, you will be left with a double result, as shown in the 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 double

+1
source share

First you need to convert the value to a floating point type, otherwise you will do integer division.

Example in C #:

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

(A cast is not really needed in this code, since dividing by a floating-point number will cause the value to match, but it will be clearer to write a listing in the code, since this is what actually happens.)

0
source share

All Articles