【问题标题】:How can I format this number correctly using PHP?如何使用 PHP 正确格式化这个数字?
【发布时间】:2019-02-14 09:02:40
【问题描述】:

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

例如,保存在我的数据库中的价格是 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 ,为什么?

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

【问题讨论】:

  • 你必须从一个合理的数学数字格式开始这个过程,即123.45。因此,您应该使用适当的数字格式将数字存储在数据库中,然后仅在您的表示层中将它们格式化为区域设置所需的任何格式

标签: php numbers


【解决方案1】:

问题在于,首先价格“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

【讨论】:

    【解决方案2】:

    更改输入数字格式。

    <?php
    echo number_format("1000000")."<br>";
    echo number_format("1000000",2)."<br>";
    echo number_format("1000000",2,",",".");
    ?>
    

    输出:-

    1,000,000
    1,000,000.00
    1.000.000,00
    

    【讨论】:

      【解决方案3】:

      这会将您的数字四舍五入到最接近的 10 倍数:

      $n = 123.45;
      
      $multiple = 10;
      
      $result = (ceil($n)%$multiple === 0) ? ceil($n) : round(($n+$multiple/2)/$multiple)*$multiple;
      
      echo $result;
      

      然后number_format() 将其转换为字符串以使用分隔符 (,.) 显示。在不同的位置,它们用逗号分隔小数,用逗号分隔千位,在其他位置反之亦然,所以我通常将这些参数排除在外,因为它们是可选的,我认为它可能会根据查看它的机器上的语言环境设置而改变但我不确定。

      所以我要补充:

      $display_result = number_format($result,2);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-13
        • 2018-08-25
        • 1970-01-01
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        • 2021-04-24
        • 1970-01-01
        相关资源
        最近更新 更多