php 计算给出了 1500000-20% 的奇怪结果 [英] php calculation gives a weird result for 1500000-20%
问题描述
可能是我瞎了或傻了,但看看我的功能:
May be I might be blind or silly, but look at my function:
function max_min_twenty($value) {
if ((int)$value == 0) {
return "0";
} else {
$percent_val = ((int)$value / 100) * 20;
$maxvalue = (int)$value + $percent_val;
$minvalue = (int)$value - $percent_val;
$returnvalue = round($minvalue)."-".round($maxvalue);
return $returnvalue;
}
}
看来这真的很容易!它应该像它应该的那样工作,但是如果我的 $value 是 1500000,它会为我返回 1,2E+6 $minvalue - 效果很好如果我选择不同的数字,或者如果我将百分比更改为 19 或 21.那是什么?
Seems that this is really easy! It works like it should, but if my $value is 1500000 it gives me back 1,2E+6 for $minvalue - It does well if I choose a different number or if I change the percent to 19 or 21. Whats that?
它在 PHP 版本 5.2.4-2ubuntu5.27 上运行
Its running on PHP Version 5.2.4-2ubuntu5.27
推荐答案
将数字格式化为整数?round
返回一个 float,所以我相信默认格式是混淆"或遇到边缘情况"并恢复显示科学记数法.(我无法在 ideone 上触发问题 - 它可能特定于特定的 PHP 版本/环境 - 但是症状适合.)
Format the number explicitly as an integer? round
returns a float and so I believe the default formatting is "getting confused" or "hitting an edge case" and reverts to displaying scientific notation. (I can't trigger the problem on ideone - it might be specific to a particular PHP version/environment - but the symptoms fit.)
尝试 sprintf:
return sprintf("%d-%d", $minvalue, $maxvalue);
(我删除了 round
因为 %d
强制将参数视为整数;但是,舍入规则可能存在细微差别......我不不知道.)
(I removed round
as the %d
forces the arguments to be treated as integers; however, there might be subtle differences in the rounding rules .. I don't know.)
这篇关于php 计算给出了 1500000-20% 的奇怪结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!