Php 方程:变量减去相同的四舍五入变量,可能吗?
Php equation: variable minus same rounded variable, possible?
我需要以两种方式回显数字(变量),我需要有关此等式代码的帮助。
示例:
变量为 5003
第一个回显必须是:5000(四舍五入)
第二个回显必须是四舍五入的数字:3
所以我想知道我是否以及如何实现这个等式,我在考虑以下几行:变量(5003)减去舍入变量(5000)等于 3
这样的话,如果变量是 15009
拳头将是15000
第二个是 9
我希望这是有道理的,谢谢你的帮助
您应该查看 roundPHP 函数:
您可以像这样使用负小数点:
round(5003, -3); // returns 5000
round(15009, -3); // returns 15000
要找出差异,您可以这样做:
$input = 5003
$x = $input;
$y = round($input, -3);
$z = $x - $y; // z is now 3
PHP不是数学语言,所以不能帮你解方程。
您可以像这样制定更通用的解决方案:
$inputs = [
5003,
15009,
55108,
102010
];
foreach ($inputs as $input) {
$decimals = floor(log10($input)) - 1;
$rounded = round($input, -1 * $decimals);
echo "$input - $rounded = " . ($input - $rounded) . PHP_EOL;
}
输出:
5003 - 5000 = 3
15009 - 15000 = 9
55108 - 55000 = 108
102010 - 100000 = 2010
假设您要四舍五入最后三位数字:
$input = 5003;
$rounded = (int)(5003 / 1000) * 1000;
$rest = $input - $rounded;
echo($rounded . "\n" . $rest);
这导致:
5000
3
我需要以两种方式回显数字(变量),我需要有关此等式代码的帮助。 示例:
变量为 5003
第一个回显必须是:5000(四舍五入)
第二个回显必须是四舍五入的数字:3
所以我想知道我是否以及如何实现这个等式,我在考虑以下几行:变量(5003)减去舍入变量(5000)等于 3
这样的话,如果变量是 15009
拳头将是15000 第二个是 9
我希望这是有道理的,谢谢你的帮助
您应该查看 roundPHP 函数:
您可以像这样使用负小数点:
round(5003, -3); // returns 5000
round(15009, -3); // returns 15000
要找出差异,您可以这样做:
$input = 5003
$x = $input;
$y = round($input, -3);
$z = $x - $y; // z is now 3
PHP不是数学语言,所以不能帮你解方程。
您可以像这样制定更通用的解决方案:
$inputs = [
5003,
15009,
55108,
102010
];
foreach ($inputs as $input) {
$decimals = floor(log10($input)) - 1;
$rounded = round($input, -1 * $decimals);
echo "$input - $rounded = " . ($input - $rounded) . PHP_EOL;
}
输出:
5003 - 5000 = 3
15009 - 15000 = 9
55108 - 55000 = 108
102010 - 100000 = 2010
假设您要四舍五入最后三位数字:
$input = 5003;
$rounded = (int)(5003 / 1000) * 1000;
$rest = $input - $rounded;
echo($rounded . "\n" . $rest);
这导致:
5000
3