【问题标题】:PHP Scientific Notation ShorteningPHP 科学记数法缩短
【发布时间】:2023-03-13 15:13:01
【问题描述】:

我正在这里寻找一个优雅的解决方案(如果存在的话)。

我有一堆数字,小数位数不限。如果它有超过 8 个尾随零,我想强制数字使用 8 位小数,即

0.000000004321

这将被转换为:

0.00000001

但我不想使用数字格式,因为如果我使用数字格式将其强制为 8 位小数,那么没有 8 位小数的数字将如下所示:

1.00000000

我宁愿这些看起来像(对于金额 >= 1):

1.00700000 -> 1.01

对于

0.00300000 -> 0.003

如果数字小于 1,即 0.XX,我希望它具有更高的精度(最多 8 个,去掉所有尾随的 0)。

所以,再一次,这里有几个例子来说明清楚:

1.00300000  -> 1.01 (maintain and round 2p for amounts >= 1)
0.00300000  -> 0.003 (maintaining precision, removing trailing 0's for amounts < 1)

1.00300001  -> 0.01 (maintain and round 2dp for amounts >= 1)
0.00300001  -> 0.00300001 (no change needed on this)
0.003000017 -> 0.00300002 (rounds upward to 8dp because it's < 1)

1.000000002 -> 1.00 (maintain and round 2dp for amounts >= 1)
0.000000002 -> 0.00000001 (rounds upward to 8dp because it's < 1)

目前,由于小数位数,我的非常小的数字也以科学计数法显示。所以这是我需要担心的另一件事(即转换科学记数法来进行计算)。

我知道我可以用一堆通用逻辑来做到这一点,但这似乎是一种老套的做事方式,当然有一些很好的解决方案。

谢谢。

【问题讨论】:

  • round、ceil 和/floor 在这种情况下不起作用?

标签: php decimal precision rounding scientific-notation


【解决方案1】:

四舍五入到第二位:ceil()

要删除结尾的零:rtrim()

if($number >= 1)
{
    ceil to 2nd decimal place
}

else //when the number is less than 1
{
    ceil to 8th place
    try rtrim with '0' to remove ending zeros if there is any
}

【讨论】:

    猜你喜欢
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多