簡體   English   中英

四舍五入無理數

[英]Rounding irrational numbers

所以:)

我有一些數字。 我想根據之后的數字四舍五入. 標志。 問題是我不知道會有多少個零.

我知道函數toPrecision()toFixed()但它們必須傳遞參數。 因此,我必須知道小數點后需要多少符號,但我不知道。

我想實現什么?

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

我該如何實現?

嘗試使用此:

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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM