0

I've done the following subtraction:

float result = 0.53f - 0.5293873f;

But the result of subtraction is wrong, I expect the result to be 0.0006127 but result is 6.1267614E-4

This question may be a duplicate, but I did not find the answer after very search.

I want to know what is the cause of this problem and what is the solution

Thanks.

saleh gholamian
  • 178
  • 2
  • 12
  • The scientific notation for 0.00061267614. As `float` has a precision of 7-8 digits the approximation error is to be expected. – Joop Eggen Jan 08 '20 at 10:12
  • Thanks Joop Eggen, but what is solution? – saleh gholamian Jan 08 '20 at 10:20
  • `new BigDecimal("0.53").substract("0.5293873").toPlainString()` = exact precision and no scientific notation. – Joop Eggen Jan 08 '20 at 11:04
  • Thanks, I've also read where this error only occurs when printing and the result value is correct and can be used – saleh gholamian Jan 08 '20 at 12:06
  • No, every floating point (float, double) is a sum of powers of 2. So 0.25 is precise, but 0.1 which would be an infinite sum of (negative) powers of 2 is just an approximation. But on printing one could the number a bit repaired. Use double/float for scalable graphics and BigDecimal for financial purposes. – Joop Eggen Jan 08 '20 at 12:13
  • Thank you mr Joop Eggen – saleh gholamian Jan 08 '20 at 19:13

0 Answers0