1

I have wrote a function to calculate the payment fee in my website but it gives different results in javascript and php. You should copy this code to a htm/html file.

the code in bug.php :

<table style="background-color:#ccc; width:600px; font-family:Tahoma">
<tbody><tr style="background-color:#00CCFF"><td>original number</td><td>phpToFixed()</td><td>jsToFixed()</td><td>phpCalc</td><td>jsCalc</td></tr>
<script>
function jsToFixed(i) {
return(Math.floor(i * 100) / 100);
}
function jsCalc(ob){
    val=jsToFixed(ob);
    if(val>0&&val!=''){
    result = jsToFixed(0.95*ob);
    }else{

    result = 0;
    }
    if(result==val&&result!=0){
    result-=0.01;
    }
return result;
}
<?php
function phpToFixed($amount){
$inp= floor($amount * 100) / 100;
return $inp;
}
function phpCalc($amount){
$inp= phpToFixed($amount);

    if($inp>0&&$inp!=''){
$result = phpToFixed($amount*0.95);

    }else{
$result = 0;
    }
if($result==$inp&&$result!=0){
$result-=0.01;
}
return $result;
}
for($i=0;$i<1;$i+=0.009){
?>
document.write("<tr><td class='org'><? echo $i; ?> </td><td class='fix'> <? echo phpToFixed($i); ?> </td><td class='fix'>"+jsToFixed(<? echo $i; ?>)+"</td><td class='calc'>"+jsCalc(<? echo $i; ?>)+"</td><td class='calc'>"+<? echo phpCalc($i); ?>+" </td></tr> ");
<?php
}
?>
</script>
</tbody>
</table>

Any one can figure out?

AMIN Gholibeigian
  • 337
  • 2
  • 6
  • 20
  • 1
    http://stackoverflow.com/questions/1458633/elegant-workaround-for-javascript-floating-point-number-problem might be helpful – Loktar Apr 19 '12 at 19:29

1 Answers1

7

When dealing with currency, ALWAYS use integer mathematics. For example, if your currency is US Dollars, ALWAYS calculate prices in cents.

Floating point numbers CANNOT represent 0.01 exactly. It's no surprise, therefore, that you're getting issues.

Whereas, integers CAN represent 1 exactly, and when you're done calculating you can just divide by 100 and round to two decimal places - any FP errors would be too small to have any effect.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592