php - 如何使用 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 ,为什么?
我希望所有数字都具有相同的格式,逗号后面有两位小数的数字,无论这些数字是零还是更多。
解决方案
问题是,首先价格“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
推荐阅读
- java - 使用 repaint() 在添加到 JFrame 的 JPanel 上绘图
- python - 在 if 语句中访问列表中元组的值
- html - 在 Bootstrap 手风琴中左右对齐文本
- c# - 如何递归返回 C# 中的所有 args 输入
- geospatial - 在一定长度上划分开放街道地图中的路线
- python - 文本边缘锯齿形效果去除(或找到图像区域的主色)
- javascript - Javascript创建循环变量
- asp.net-mvc - 我们如何将列表、字符串和整数数据传递给 MVC 中的 API
- java - 在构造函数 Junit5 java 中没有为参数 XXXX 注册 ParameterResolver
- .net - 可以使用 .NET WebSockets 作为“客户端”连接到“HTTP 长轮询服务器”吗?