I have a Double
object which loses the exact value when being converted to a long
value.
Double d = 1.14*100
System.out.println(d.longValue());
The above statement would print: 113
.
I want 114
to be printed.
I have a Double
object which loses the exact value when being converted to a long
value.
Double d = 1.14*100
System.out.println(d.longValue());
The above statement would print: 113
.
I want 114
to be printed.
If you need the exact 114 value you ned to use Math.round
:
double d = 1.14*100;
System.out.println(Math.round(d));
If you are looking for an integer / long value representation with the value you are expecting, you can use this:
Math.round(1.14 * 100)
Firstly, a double
is not exact. Next, when casting a double
/float
to a long
/int
, the decimal part is dropped (not rounded).
To get the nearest value, you'll need to round it:
System.out.println(Math.round(d));