ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
2.2. Comparing Floating-Point NumbersProblemFloating-point arithmetic isn't precise. You want to compare two floating-point numbers and know if they're equal when carried out to a certain number of decimal places. Most of the time, this is the way you should compare floating-point numbers for equality. SolutionUse # equal(NUM1, NUM2, ACCURACY) : returns true if NUM1 and NUM2 are # equal to ACCURACY number of decimal places sub equal { my ($A, $B, $dp) = @_; return sprintf("%.${dp}g", $A) eq sprintf("%.${dp}g", $B); } Alternatively, store the numbers as integers by assuming the decimal place. DiscussionYou need the If you have a fixed number of decimal places, as with currency, you can sidestep the problem by storing your values as integers. Storing $wage = 536; # $5.36/hour
$week = 40 * $wage; # $214.40
printf("One week's wage is: \$%.2f\n", $week/100);
It rarely makes sense to compare to more than 15 decimal places. See AlsoThe |