PHP字符串四舍五入到小数点后两位的正确方法是什么?
$number = "520"; // It's a string from a database
$formatted_number = round_to_2dp($number);
echo $formatted_number;
输出应该是520.00;
round_to_2dp()函数应该如何定义?
PHP字符串四舍五入到小数点后两位的正确方法是什么?
$number = "520"; // It's a string from a database
$formatted_number = round_to_2dp($number);
echo $formatted_number;
输出应该是520.00;
round_to_2dp()函数应该如何定义?
当前回答
这里我得到两个小数。(点)使用函数…
function truncate_number($number, $precision = 2) {
// Zero causes issues, and no need to truncate
if (0 == (int)$number) {
return $number;
}
// Are we negative?
$negative = $number / abs($number);
// Cast the number to a positive to solve rounding
$number = abs($number);
// Calculate precision number for dividing / multiplying
$precision = pow(10, $precision);
// Run the math, re-applying the negative value to ensure
// returns correctly negative / positive
return floor( $number * $precision ) / $precision * $negative;
}
上述函数的结果:
echo truncate_number(2.56789, 1); // 2.5
echo truncate_number(2.56789); // 2.56
echo truncate_number(2.56789, 3); // 2.567
echo truncate_number(-2.56789, 1); // -2.5
echo truncate_number(-2.56789); // -2.56
echo truncate_number(-2.56789, 3); // -2.567
新的正确答案
使用PHP本地函数bcdiv
echo bcdiv(2.56789, 1, 1); // 2.5
echo bcdiv(2.56789, 1, 2); // 2.56
echo bcdiv(2.56789, 1, 3); // 2.567
echo bcdiv(-2.56789, 1, 1); // -2.5
echo bcdiv(-2.56789, 1, 2); // -2.56
echo bcdiv(-2.56789, 1, 3); // -2.567
其他回答
另外,
$padded = sprintf('%0.2f', $unpadded); // 520 -> 520.00
bcdiv($number, 1, 2) // 2 varies for digits after the decimal point
这将显示小数点后的两位数字。
优势:
如果你只想在浮点值后显示两个数字,而不是int,那么使用这个。
我自己做。
$decimals = 2;
$number = 221.12345;
$number = $number * pow(10, $decimals);
$number = intval($number);
$number = $number / pow(10, $decimals);
这里我得到两个小数。(点)使用函数…
function truncate_number($number, $precision = 2) {
// Zero causes issues, and no need to truncate
if (0 == (int)$number) {
return $number;
}
// Are we negative?
$negative = $number / abs($number);
// Cast the number to a positive to solve rounding
$number = abs($number);
// Calculate precision number for dividing / multiplying
$precision = pow(10, $precision);
// Run the math, re-applying the negative value to ensure
// returns correctly negative / positive
return floor( $number * $precision ) / $precision * $negative;
}
上述函数的结果:
echo truncate_number(2.56789, 1); // 2.5
echo truncate_number(2.56789); // 2.56
echo truncate_number(2.56789, 3); // 2.567
echo truncate_number(-2.56789, 1); // -2.5
echo truncate_number(-2.56789); // -2.56
echo truncate_number(-2.56789, 3); // -2.567
新的正确答案
使用PHP本地函数bcdiv
echo bcdiv(2.56789, 1, 1); // 2.5
echo bcdiv(2.56789, 1, 2); // 2.56
echo bcdiv(2.56789, 1, 3); // 2.567
echo bcdiv(-2.56789, 1, 1); // -2.5
echo bcdiv(-2.56789, 1, 2); // -2.56
echo bcdiv(-2.56789, 1, 3); // -2.567
你可以使用number_format():
return number_format((float)$number, 2, '.', '');
例子:
$foo = "105";
echo number_format((float)$foo, 2, '.', ''); // Outputs -> 105.00
这个函数返回一个字符串。