0

I tried to print the float variable's value.

But the result is weird...

float num1 = 45.9f;
float num2 = 32.1f;

System.out.printf("%f, %f", num1, num2);

// Expected: 45.9, 32.1
// Result: 45.900002, 32.099998

Why does appear like that??

Sorry for the question...

Raju Ahmed
  • 1,282
  • 5
  • 15
  • 24
MayB
  • 11
  • 3
  • Use BigDecimal, although there are drawbacks like it being slower and harder to do simple math with. if you're dealing with money go with BigDecimal, if not then float or double is good enough, just round the number. – crimson589 Nov 04 '21 at 03:47
  • Because there are infinitely many real numbers, and only finitely many combinations of 32 bits. Therefore, most real numbers can't be exactly represented with a float. – Dawood ibn Kareem Nov 04 '21 at 03:47
  • 1
    Also, no need to say "sorry for the question". Questions are what we deal with on Stack Overflow. It's non-questions that upset us. – Dawood ibn Kareem Nov 04 '21 at 03:52
  • If you want a perfect value, use `BigDecimal`. If you want speed of execution, use the floating-point types, `float`/`Float` or `double`/`Double`. Choose one, [accuracy or speed](https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems); you cannot have both. – Basil Bourque Nov 04 '21 at 04:57
  • If you want to print only upto 1 decimal places then you can use System.out.printf("%.1f , %.1f",num1,num2); – shockwave Nov 04 '21 at 06:47

0 Answers0