0

Am I missing something basic in Java Math calculations for float numbers ? I can use Math function round(), However I want accurate value 6.4 as the input given is simple and doesn't have many values after the decimal point.

System.out.println(1.8f+1.0f+1.9f+1.7f); // Expected 6.4 but actual is 6.3999999999999995 how ?
Uday Kiran
  • 487
  • 2
  • 9
  • 29
  • 1
    the short answer being "no, 6.4 is absolutely not expected" because IEEE floating point numbers are lossy approximations for decimal numbers. Just because you write some number, doesn't mean the floating point value will actually _be_ that number. – Mike 'Pomax' Kamermans Feb 26 '20 at 06:41
  • What is the reason you use floating points here? – aydinugur Feb 26 '20 at 06:46
  • 1
    @aydinugur - probably no reason. It is an example. Besides, it doesn't make any difference if the OP uses `float` or `double`. The same sort of thing occurs with all primitive binary floating point types. – Stephen C Feb 26 '20 at 06:47
  • Thank you guys for your reply, So we need to use BigDecimal type to sum the floating decimals in Java ? – Uday Kiran Feb 27 '20 at 18:46

0 Answers0