PHP舍入问题(5.2.3)? [英] PHP rounding problem (5.2.3)?

查看:52
本文介绍了PHP舍入问题(5.2.3)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我是否发现 PHP 中的舍入有问题,特别是 5.2.3(我目前不确定其他版本):

I'm wondering if I found an issue with the rounding in PHP, specifically 5.2.3 (I'm not sure about other versions at the moment):

$t = 0;

$taxAmount = (5.000 / 100) * 0.7;
$t += $taxAmount;

var_dump($t); // float(0.035)
var_dump(round($t, 2)); // float(0.03)
var_dump(number_format($t, 2)); // string(4) "0.03"

对我来说 0.035 应该四舍五入到 0.04 还是我疯了?

To me 0.035 should round to 0.04 or am I just crazy?

编辑

感谢 NebyGemini 的回答,我想我会改为这样做:

Thxs to NebyGemini's answer, I figured I would do this instead:

$t = 0;

$taxAmount = bcmul(bcdiv(5.000, 100, 3), 0.7, 3);
$t += $taxAmount;

var_dump($t); // float(0.035)
var_dump(round($t, 2)); // float(0.04)
var_dump(number_format($t, 2)); // string(4) "0.04"

哪个完美.

顺便说一句,我正在计算购物车中的税款.订单总额为 0.70(70 美分),税费为 5%.

BTW, I'm calculating a tax in a shopping cart. The order total is the 0.70 (70 cents) and the tax is 5%.

编辑

感谢Ignacio Vazquez-Abrams 的回答,这是为了说明问题所在:

Thxs to Ignacio Vazquez-Abrams's answer, this is to show where the problem lies:

printf('%.18F', 5.000 / 100 * 0.7);

推荐答案

浮动是邪恶的.

引用关于浮点数的PHP手册文档:

Quoting the PHP manual documentation on Floating Point numbers:

所以永远不要相信浮点数结果到最后一位,也不要比较浮点数是否相等.如果需要更高的精度,任意精度数学函数gmp 功能可用.

So never trust floating number results to the last digit, and never compare floating point numbers for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

如果您想知道浮动的原因和方式,我建议您观看:
关于 JavaScript 数字你不想知道的一切

If you want to know why and how floats work I recommend watching:
Everything you didn't want to know about JavaScript numbers

这篇关于PHP舍入问题(5.2.3)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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