2013-04-06 95 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 
}