本文主要是介绍php5.4 round,php的round四含五入问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
静坐常思己过,闲谈莫论人非,能受苦乃为志士,肯吃亏不是痴人,敬君子方显有德,怕小人不算无能,退一步天高地阔,让三分心平气和,欲进步需思退步,若着手先虑放手,如得意不宜重往,凡做事应有余步。持黄金为珍贵,知安乐方值千金,事临头三思为妙,怒上心忍让最高。切勿贪意外之财,知足者人心常乐。若能以此去处事,一生安乐任逍遥。
php的round四含五入问题
作者:大鹏 发布于:2007-6-6 16:34 Wednesday
分类:PHP&MySql
代码:
[codes=php]<?php
echo "round(5.005,2)=".round(5.005,2)."\n";
echo "round(5.015,2)=".round(5.015,2)."\n";
echo "round(5.025,2)=".round(5.025,2)."\n";
echo "round(5.035,2)=".round(5.035,2)."\n";
echo "round(5.045,2)=".round(5.045,2)."\n";
echo "round(5.055,2)=".round(5.055,2)."\n";
echo "round(5.065,2)=".round(5.065,2)."\n";
echo "round(5.075,2)=".round(5.075,2)."\n";
echo "round(5.085,2)=".round(5.085,2)."\n";
echo "round(5.095,2)=".round(5.095,2)."\n";
$m=0.000000000000001;
echo "\n";
echo "round(5.005+{$m},2)=".round(5.005+$m,2)."\n";
echo "round(5.015+{$m},2)=".round(5.015+$m,2)."\n";
echo "round(5.025+{$m},2)=".round(5.025+$m,2)."\n";
echo "round(5.035+{$m},2)=".round(5.035+$m,2)."\n";
echo "round(5.045+{$m},2)=".round(5.045+$m,2)."\n";
echo "round(5.055+{$m},2)=".round(5.055+$m,2)."\n";
echo "round(5.065+{$m},2)=".round(5.065+$m,2)."\n";
echo "round(5.075+{$m},2)=".round(5.075+$m,2)."\n";
echo "round(5.085+{$m},2)=".round(5.085+$m,2)."\n";
echo "round(5.095+{$m},2)=".round(5.095+$m,2)."\n";
?> [/codes]
结果:
round(5.005,2)=5.01
round(5.015,2)=5.01
round(5.025,2)=5.03
round(5.035,2)=5.04
round(5.045,2)=5.05
round(5.055,2)=5.06
round(5.065,2)=5.07
round(5.075,2)=5.08
round(5.085,2)=5.09
round(5.095,2)=5.1
round(5.005+1E-015,2)=5.01
round(5.015+1E-015,2)=5.02
round(5.025+1E-015,2)=5.03
round(5.035+1E-015,2)=5.04
round(5.045+1E-015,2)=5.05
round(5.055+1E-015,2)=5.06
round(5.065+1E-015,2)=5.07
round(5.075+1E-015,2)=5.08
round(5.085+1E-015,2)=5.09
round(5.095+1E-015,2)=5.1
PHP手册:
例子 1. round() 例子
[codes=php]<?php
echo round(3.4); // 3
echo round(3.5); // 4
echo round(3.6); // 4
echo round(3.6, 0); // 4
echo round(1.95583, 2); // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2); // 5.04
echo round(5.055, 2); // 5.06
?> [/codes]
注意
在对正好一半的分数进行舍入时 round() 在偶数次舍去,在奇数次进位。如果你想迫使它对 .5(或 .05)总向一个方向舍入,加上或减去一个很小的因子。对一半值舍去对另一半值进一的背后原因是避免传统的银行问题,即如果总是舍去则银行从顾客那里多拿了钱,如果总是进一则银行最终会损失了钱。对此平均舍入则在统计上达到了平衡。
PHP手册中
echo round(5.045, 2); // 5.04
echo round(5.055, 2); // 5.06
而我代码的结果却是:
round(5.045,2)=5.05
round(5.055,2)=5.06
round(5.005,2)=5.01
round(5.015,2)=5.01
round(5.025,2)=5.03
round(5.035,2)=5.04
round(5.045,2)=5.05
round(5.055,2)=5.06
从这个结果看,也不明白"在偶数次舍去,在奇数次进位"是一个什么样的原则,
请各位PHP强人指教.
et_highlighter
发表评论
昵称
邮箱
网址
干净网络从你做起,切勿黏贴小广告
这篇关于php5.4 round,php的round四含五入问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!