[英]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.