php浮点数计算小数点后2位

php float calculation 2 decimal point(php浮点数计算小数点后2位)
本文介绍了php浮点数计算小数点后2位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一道数学计算题.

$a = 34.56

$b = 34.55

$a做一些计算得到这个数字

$a do some calculation to get this figure

$b 正在四舍五入到最接近的 0.05 以获得这个数字

$b is doing rounding to the nearest 0.05 to get this figure

发生了什么

$c = $b - $a

应该是-0.01,但是我回显了$c,它显示了-0.00988888888888

supposedly it be -0.01, but I echo out the $c, which shows -0.00988888888888

我尝试使用number_format($c, 2),但是输出是0.00,

I try to use number_format($c, 2), but the output is 0.00,

如何确保 $a$b 正好是 2 位小数,后面没有隐藏数字.

how can I make sure $a and $b is exactly 2 decimals, no hidden number at the back.

在我的php知识中,number_format只能格式化显示,但值并不是真正的2位小数,

in my php knowledge, number_format is only able to format the display, but the value is not really 2 decimal,

我希望我能从这里得到帮助.这让我很沮丧.

I hope I can get help from here. This really frustrated me.

推荐答案

试试 sprintf("%.2f", $c);

浮点数以 IEEE 表示法表示,基于 2 的幂,因此终止十进制数可能不是终止二进制数,这就是您得到尾随数字的原因.

Floating point numbers are represented in IEEE notation based on the powers of 2, so terminating decimal numbers may not be a terminating binary number, that's why you get the trailing digits.

正如可变长度编码器所建议的那样,如果您知道所需的精度并且它不会改变(例如,当您处理金钱时),最好只使用定点数,即将数字表示为美分而不是比美元

As suggested by Variable Length Coder, if you know the precision you want and it doesn't change (e.g. when you're dealing with money) it might be better to just use fixed point numbers i.e. express the numbers as cents rather than dollars

$a = 3456;

$b = 3455;

$c = $b - $a;

sprintf ("%.2f", $c/100.0);

这样,如果您在打印前进行大量计算,就不会出现任何舍入错误.

This way, you won't have any rounding errors if you do a lot of calculations before printing.

这篇关于php浮点数计算小数点后2位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)