PHP Division results in automatically rounded up number

限于喜欢 提交于 2021-01-29 16:17:48

问题


I have a simple division:

72 / 193

Excel is giving me result of

0.373056994818653

While PHP round it up to

0.373056994819

My question is - how can I make PHP to give me the exact number instead of a rounded up one?


回答1:


It isn't a question of being 'exact' or not, it is about precision. Wolfram Alpha has a much larger precision for your answer.

You need to change the precision of your php configuration to suit how many units you need after the decimal. I cannot find the largest precision PHP has to offer, but I'm sure there is a limit.




回答2:


The exact number for that is an infinite decimal. You can never get a complete absolute value for that, because that would require infinite memory, something that we sadly do not have access to.

Take a look at bcdiv, which allows for very long ints and floating point numbers

For all practical intents and purposes, however, if two numbers are within 1*10-8 or so, you should be able to consider them equal

You can do this like this:

if(abs($num1-$num2)<=1e-8){
    echo "They are equal";
}


来源:https://stackoverflow.com/questions/20244762/php-division-results-in-automatically-rounded-up-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!