[英]perform round function without using round() in php
不使用round()函数perfrom在PHP中的round()
$a = "123.45785";
$v = round($a);
output: 123.46;
它已经通过回合函数完成,但我想在不使用回合和number_format()函数的情况下获得输出。
这是一种使用算术的方法:
function my_round($num, $places = 2) {
// Multiply to "move" decimals to the integer part
// (Save one extra digit for rounding)
$num *= pow(10, $places + 1);
// Truncate to remove decimal part
$num = (int) $num;
// Do rounding based on the last digit
$lastDigit = $num % 10;
if ($lastDigit >= 5)
$num += 10;
// Remove last digit
$num = (int) ($num/10);
// "Move" decimals in place, and you're done
$num /= pow(10, $places);
return $num;
}
你有sprintf
。
$a = "123.45785";
echo sprintf("%01.2f", $a); // output: 123.46
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.