2014-04-15 19 views
1

SO :)舍入無理數

我有一些數字。我想在.符號後根據數字將它們四捨五入。問題是我不知道在.之後會有多少零。

我知道函數toPrecision()toFixed()但他們必須通過參數。所以我必須知道在小數點後需要多少符號,但我不知道。

我想實現什麼?

+++++++++++++++++++++++++++++++++++ 
+ before   + after  + 
+++++++++++++++++++++++++++++++++++ 
+ 0.0072512423324 + 0.0073  + 
+ 0.032523   + 0.033  + 
+ 0.000083423342 + 0.000083 + 
+ 15.00042323  + 15.00042 + 
+ 1.0342345   + 1.034  + 
+++++++++++++++++++++++++++++++++++ 

我該如何做到這一點?

+0

我不明白,有多少個數字你要根據數字* N *金額四捨五入小數點後? – thecoder16

+0

所以你最多需要2個非零數字? –

+0

@code16,實現我想要的我可以使用'toFixed'函數。問題是我不知道這個函數的參數。對於每個新的號碼,我想圍繞這個數字是不同的。這就是問題所在。如何檢測小數點後的數字位數,以'toFixed(foundParam)'結尾;' –

回答

2

嘗試使用這樣的:

function roundAfterZeros(number,places){ 
    var matches=number.toString().match(/\.0*/); 
    if(!matches)return number.toString(); 
    return number.toFixed(matches[0].length-1+places); 
} 

這裏有一個解釋

var matches = number.toString().match(/\.0*/)檢查點(.)後零(0)。

if(!matches)return number.toFixed(places);如果沒有點(.),它必須是一個整數,所以我們只是返回它(作爲一致性字符串)。

return number.toFixed(matches[0].length-1+places);如果它是一個小數,我們將它舍入到零後的最接近的數字(0)。

然後,像roundAfterZeros(0.000083423342,2)運行:

0.000083423342 to "0.000083" 
1.0342345 to  "1.034" 
1 to    "1" 
0.5 to   "0.50" 
-300 to   "-300" 
+0

最後的* 1是什麼?假設行爲應該與'toFixed()'相似,結果應該保持一個字符串。 –

+0

那麼這種方法工作。看起來很髒> _

+0

好的。我拿出'* 1'作爲一個字符串並添加一個解釋。對不起:) :) –