假设我有
$number = .20
当我运行脚本时,PHP会自动删除零,只留下.2。怎么解决?
我知道.2和.20是相同的,但是我需要这个数字的零来使用它。
// The number to display
$n = .2;
// The number of decimal places
$places = 2;
// Print the number to the desired precision.
echo number_format($n, $places)
$num = "0.20";
echo "Num is:".$num;
//或者
$num = number_format(0.20, 2);
echo "Num is:".$num;
以上示例展示了两种方式将数字转换成指定格式的字符串。第一种方式是使用普通的字符串拼接,而第二种方式则使用了number_format函数。$number = '.20';
你可以使用以下方式格式化数字:
$num_decimal_places = 2; // This will give .20
$formatted = number_format($number, $num_decimal_places, '.', '');
.20 是一个浮点字面量。在解析后,它会被转换为浮点数。您可以稍后使用以下代码将其格式化为两位小数:
sprintf("%.2f\n", $number);
但是如果你根本不将它作为数字使用,那么Mike是正确的,你应该将它保留为字符串。