Converting double to long without losing the exact value

I have a Double object that loses the exact value when converted to a long value.

 Double d = 1.14*100 System.out.println(d.longValue()); 

The above statement will print: 113 .

I want to print 114 .

thanks

+6
source share
4 answers

If you need the exact value of 114 that you used to use Math.round :

 double d = 1.14*100; System.out.println(Math.round(d)); 
+6
source

If you are looking for a representation of an integer / long value with the value you expect, you can use this:

 Math.round(1.14 * 100) 
+3
source

Firstly, a double not exact. Then, when double / float pressed on a long / int , the decimal part is discarded (not rounded).

To get the closest value, you need to round it:

 System.out.println(Math.round(d)); 
+1
source

try it

 Long.parseLong( String.format( "%.0f",doublevalue ) ) ; 
+1
source

Source: https://habr.com/ru/post/957705/


All Articles