Subtracting close together numbers in php
Why does
<?php echo 194.95-194.94; ?>
开发者_StackOverflow中文版
output
0.0099999999999909
What am i missing here? This is php 5.2.
The issue is that you cannot represent 0.01 exactly in floating point.
Have a look at what every programmer should know about floating point for a great explanation of why this is, and what to do about it.
While Mark's answer is okay, it may still leave you wondering why you got the answer you did. For example, try
<?php echo 0.01; ?>
PHP happily prints 0.01
.
In your case 194.95
and 194.94
were both stored in as-close-a-binary-form as could be accommodated in IEEE 754, and their difference was too far away from the basic 0.01
that could be rendered "properly".
Try out your example on an online calcuator such as http://babbage.cs.qc.edu/IEEE-754/Decimal.html. Should be interesting.
精彩评论