PHP去除末尾零?

3

假设我有

$number = .20

当我运行脚本时,PHP会自动删除零,只留下.2。怎么解决?
我知道.2和.20是相同的,但是我需要这个数字的零来使用它。
5个回答

3
我唯一能想到需要尾随0的情况是显示数字。可以按以下方式打印.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)

3

$num = "0.20";
echo "Num is:".$num;
//或者 $num = number_format(0.20, 2); echo "Num is:".$num;
以上示例展示了两种方式将数字转换成指定格式的字符串。第一种方式是使用普通的字符串拼接,而第二种方式则使用了number_format函数。

2
你可以将它变成字符串。
$number = '.20';

1

你可以使用以下方式格式化数字:

$num_decimal_places = 2; // This will give .20
$formatted = number_format($number, $num_decimal_places, '.', '');

0

.20 是一个浮点字面量。在解析后,它会被转换为浮点数。您可以稍后使用以下代码将其格式化为两位小数:

sprintf("%.2f\n", $number);

但是如果你根本不将它作为数字使用,那么Mike是正确的,你应该将它保留为字符串。


我使用了@erm410提到的那个。值会改变,所以我不能像Mike说的那样使用字符串。 - Alec

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接