【问题标题】:How do I add a decimal to my number?如何在我的数字中添加小数?
【发布时间】:2012-08-03 11:54:13
【问题描述】:

我正在做一些计算,最终得到65.043.5
我需要在这个数字上加一个零,以便我的数字比较有效:

$this->sub_total == $order_sub_total

我已经使用 number_format() 进行了测试:

$total = number_format($total, 2, '.');

但这给了我消息:Wrong parameter count for number_format()

我很想这样做:

$total = $total.'0';

但如果号码是35.43,我认为这是个坏主意。

那么我怎样才能给我的数字添加一个额外的小数呢?

【问题讨论】:

  • 如果你提到小数分隔符,你也必须使用千位分隔符。
  • @matt 谢谢,我不知道。我已经阅读了文档,但并不总是那么容易理解:)
  • @Dale 一些地区使用, 作为小数分隔符,因此number_format($total, 2) 并非普遍正确。为了确保 OP 得到他想要的结果,他必须使用number_format($total, 2, '.', ',');

标签: php number-formatting


【解决方案1】:

对于number_format(),您需要两个或四个参数。三人总会报错。

对您来说,以下两种方法的工作方式相同:

$total = number_format($total, 2);

$total = number_format($total, 2, '.', ',');

【讨论】:

  • 谢谢。正如@dale 还建议的那样,只需使用number_format($total, 2)就可以了。现在我明白了 number_format 是如何工作的 :)
【解决方案2】:

如果你提到小数分隔符,你也必须使用千位分隔符。

要么这样做

number_format($total, 2);

number_format($total, 2, '.', ',');

Here's the documentation.

由于某些地区使用, 作为小数分隔符,因此number_format($total, 2) 并非普遍正确。为确保获得所需的结果,您必须使用number_format($total, 2, '.', ',');

【讨论】:

    【解决方案3】:

    为什么不是一个普通的旧 $total = sprintf("%01.2f", $total)

    编辑:

    100 万次迭代计时,$n = 3.14159

    $total = sprintf("%01.2f", $n);               9.148s
    $total = number_format($n, 2);                8.296s
    $total = number_format($n, 2, ".", ",");     10.944s
    

    所以sprintf 比带有分隔符的成熟number_format 略好。

    【讨论】:

    • 因为number_format() 无需评论就能清楚表达您的意图?
    • 100 万次迭代计时,$n = 3.14159:$total = sprintf("%01.2f", $n); 9.148s $total = number_format($n, 2); 8.296s $total = number_format($n, 2, ".", ","); 10.944s 所以sprintf 比带有分隔符的成熟number_format 略好。
    • faster != better 但我明白你的意思。谈到可维护性,我更喜欢看到能立即表达作者意图的代码,而不是在 100 万次迭代中节省 2 秒的代码。
    • 一分可维护性。但我已经习惯于将 PHP 与“在可能有数百万客户的服务器上实时运行的代码”相关联,因此在代码方面力求提供最佳的性能。我再次尝试使用 4 或 5 个千位分隔符的大量数据,大约需要 5 分钟。 1.4 倍的时间。
    • 这很好。首先,我只是在回答您的“为什么不”的修辞,然后我必须澄清一下。干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2011-05-08
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    相关资源
    最近更新 更多