round() 関数を使用せずに、php の round() から実行する
$a = "123.45785";
$v = round($a);
output: 123.46;
ラウンド関数で行っていましたが、ラウンドとnumber_format()関数を使わずに出力したいです。
round() 関数を使用せずに、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