Why are floating point numbers printed so differently?

后端 未结 5 1323
有刺的猬
有刺的猬 2020-11-27 23:10

It\'s kind of a common knowledge that (most) floating point numbers are not stored precisely (when IEEE-754 format is used). So one shouldn\'t do this:

0.3 -         


        
5条回答
  •  春和景丽
    2020-11-27 23:14

    PHP automatically rounds the number to an arbitrary precision.

    Floating-point numbers in general aren't accurate (as you noted), and you should use the language-specific round() function if you need a comparison with only a few decimal places. Otherwise, take the absolute value of the equation, and test they are within a given range.

    PHP Example from php.net:

    $a = 1.23456789;
    $b = 1.23456780;
    $epsilon = 0.00001;
    if(abs($a - $b) < $epsilon) {
      echo "true";
    }
    

    As for the Ruby issue, they appear to be using different versions. Codepad uses 1.8.6, While Ideaone uses 1.9.3, but it's more likely related to a config somewhere.

提交回复
热议问题