首页 > 解决方案 > 如何使用 PHP 正确格式化这个数字?

问题描述

我有一个小数点后带有数字的数字,但由于某种原因,在格式化它时,最后两位小数总是为零。

例如,保存在我的数据库中的价格是 154,95,但我希望将 150 的数字显示为 150,00。所以我查找了 number_format() 并找到了以下信息:

number
The number being formatted.

decimals
Sets the number of decimal points.

dec_point
Sets the separator for the decimal point.

thousands_sep
Sets the thousands separator.

有了以上信息,我做到了:

echo number_format($artikel['prijs'],2,",",".");

逗号应该是小数分隔符,点应该是千位分隔符。上面代码的 154,95 的结果仍然是 154,00 ,为什么?

我希望所有数字都具有相同的格式,逗号后面有两位小数的数字,无论这些数字是零还是更多。

标签: phpnumbers

解决方案


问题是,首先价格“154,95”被转换为数字为 154,然后 number_format() 开始执行他的工作。您必须将价格存储在数据库中为 154.95,或者您必须将字符“,”替换为“。” 在调用 number_format() 之前。例子:

<?php
$a = "159.95";
$b = "12345";
$a_number = str_replace(",", ".", $a);
$b_number = str_replace(",", ".", $b);

echo number_format($a_number,2,",","."), "\n";
echo number_format($b_number,2,",","."), "\n";
?>

输出是:

159,95

12.345,00


推荐阅读