PHP加2个小数点后的数字(金额)会得出总计错误的结果 [英] PHP Adding 2 decimal points numbers (money) gives wrong results in total amount

查看:586
本文介绍了PHP加2个小数点后的数字(金额)会得出总计错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MySQL数据库中有一个客户发票表,其中有一个名为价格的DECIMAL(10,2)字段.

I have an customer invoice table in my MySQL database with a DECIMAL(10,2) field called price.

在php中获取这些值并计算总金额时,

When fetching these values in php and calculating a sum amount,

ex:在脚本中

$totalAmount = 0; // initialised them to 

   while(records){              

       $amount = $inv_amount - ($pay_amount + $onamount); //float i guess. 2.22, 14.22
       $totalAmount = $totalAmount + $amount; //float i guess. 2.22, 14.22 ..etc

    }

echo $totalAmount;时,其最终金额有轻微错误0.01,但是,当处理大约20,000个大型数据集时,此错误变得非常可观,例如200 +

when echo $totalAmount; it has a slight error in the final amount 0.01 however when dealing which large datasets around 20,000 this error becomes very considerable such as 200+

在PHP中处理价格以及这些数字时,最安全的方法是什么?还是我最终会遇到潜在的舍入错误,以及使用浮点数据类型时常见的错误?

what is the safest way to do this when dealing with prices and such with these numbers in PHP? Or will I end up with potential rounding errors and things like that which are common when working with floating point data types?

正在使用

round 
number_format

最适合此类金融应用程序的解决方案吗?

is the most suitable solution for this type of a financial application ?

推荐答案

实际上,浮点数并不精确.
要么以分计算(乘以100并以整数计算),要么使用 BC Math 进行字符串计算.

Indeed, floating point numbers are not precise.
Either calculate in cent (multiply by 100 and calculate in integers), or calculate in strings using BC Math.

这篇关于PHP加2个小数点后的数字(金额)会得出总计错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆