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,452
  • 6
  • 27
  • 36
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,407
  • 3
  • 25
  • 34
4

Try this

Long.parseLong( String.format( "%.0f",doublevalue ) ) ;
Jans
  • 11,064
  • 3
  • 37
  • 45
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
  • 10,042
  • 11
  • 48
  • 64
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
  • 412,405
  • 93
  • 575
  • 722