php calculate float

后端 未结 3 882
挽巷
挽巷 2021-01-14 12:23

I have a weird math calculation here. I hope someone will explain.

$a = 1.85/100;
$b = 1.5/100;
$c = 1.1/100;
$d = 0.4/100;
$e = 0.4/100;
$f = 0.4/100;
$g =         


        
相关标签:
3条回答
  • 2021-01-14 13:02

    You should read this article:

    What Every Computer Scientist Should Know About Floating-Point Arithmetic

    Floating point arithmetic is not exact. You should expect small errors. The answer is correct to within a small rounding error. If you need to check if a floating point number is zero it is best not to check that it is exactly equal to zero but instead to check if it is sufficiently close to zero.

    If you really need exact arithmetic, don't use floating point types. In your example you could multiply all your numbers by 100 and use integer arithmetic to get an exact answer.

    0 讨论(0)
  • 2021-01-14 13:04

    There is nothing wrong going there, there are simply rounding approximation.

    In this very cas you should multiply all your values for 1000 and do a division at the end of the calculation or, better, resort to precise calculation extension

    0 讨论(0)
  • 2021-01-14 13:11

    any idea to correct my equation to show final result 0.00 ?

    Yeah, round($i, 2)

    The "discrepancies" are usually so small, that rounding it to 2 decimals will almost always solve the problem.

    0 讨论(0)
提交回复
热议问题