2013-04-06 123 views
0

我正在寻找一个优雅的解决方案(如果存在的话)。PHP科学记数法缩短

我有一堆数字,有任意数量的小数位数。我想迫使数使用8位小数,如果它有8个以上尾随零,即

0.000000004321

将被转换为:

0.00000001

但我不想用数字格式,因为如果我把它强制8个小数的数字格式我的号码没有8位小数的样子:

1.00000000

我宁愿这只是看起来像(数量为> = 1):

1.00700000 - > 1.01

而对于金额< 1:

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) 

此刻我非常小的数以科学计数法显示,因为小数位数的了。所以这是我需要担心的另一件事情(即转换出科学计数法来进行计算)。

我知道我可以用一堆通用逻辑来做到这一点,但它看起来像是一种很冒险的做事方式,当然这里有一些很好的解决方案。

谢谢。

+0

轮,小区和/地板并不在这种情况下工作吗? – Tim 2013-04-06 03:05:25

回答

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 
}