13

I recently tested something out that I heard using the following code

public static void main(String[] args) { double x = 4.35 * 100; System.out.println(x); }.

I am interested as to why this produces 434.99999999999994 rather than 435.0 . Thanks

DreamsOfHummus
  • 735
  • 2
  • 7
  • 18

1 Answers1

18

When you type:

double x = 4.35;

x is not stored as-is. It is stored in a approaching form (probably 4.349999999 in this case).

If you want exact result, please use BigDecimal.

You can learn about the accuracy problems of floating-point technology.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
  • 1
    Even with BigDecimal, I'm facing problems. Consider this,BigDecimal bd = new BigDecimal(4.35); System.out.println(bd.multiply(new BigDecimal(6))); – Toshik Langade Jan 17 '21 at 09:31