7

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.

LW001
  • 2,217
  • 4
  • 27
  • 34
Abs
  • 458
  • 1
  • 7
  • 17

4 Answers4

7

If you need the exact 114 value you ned to use Math.round:

double d = 1.14*100;
System.out.println(Math.round(d));
Donvino
  • 2,249
  • 3
  • 24
  • 34
4

Try this

Long.parseLong( String.format( "%.0f",doublevalue ) ) ;
Jans
  • 10,901
  • 3
  • 35
  • 44
3

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)
Chris Forrence
  • 9,860
  • 11
  • 47
  • 62
1

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));
Bohemian
  • 389,931
  • 88
  • 552
  • 692