2013-09-30 100 views
2

的問題:如果你這樣做log1000你將得到的結果是log1000 = 2.9999999999999996,而不是3的JavaScript:舍入數,而不會影響結果的準確性

我試圖刪除在JavaScript eval()功能此舍入誤差不影響結果的準確性。 在格式編號功能FormatNumber(strnum)我把CheckEpsilon(strnum)哪些測試,如果數量的「右尾」是不是小量greather(假設小量的值1E-9爲C)

function FormatNumber(strnum) { 
// asf - number format: automatic(0), scientific(1) or fixed(2) notation 
// decimal - number of decimal places(0-15) 

    // First we must check if the right tail is bigger than epsilon 
    strnum = CheckEpsilon(strnum); 
    // And then we format the number 
    var x = parseFloat(strnum); 

    switch(asf) { 
     case 0:  // auto 
      strnum = x.toPrecision(); 
      break; 
     case 1:  // sci 
      strnum = x.toExponential(decimal); 
      break; 
     case 2:  // fix 
      strnum = x.toFixed(decimal); 
      break; 
    } 

    return strnum; 
} 

function CheckEpsilon(strnum) { 
// EPSILON - Difference between 1 and the least value greater than 1 that is representable. 

    var epsilon = 1e-8; 
    var x = parseFloat(strnum); 

    var expnum = x.toExponential(17); 
    // Last 10 numbers before the exponent (9 if the number is negative) 
    // we turn in to a new decimal number ... 
    var y = parseFloat("0." + expnum.slice(9,19)); 

    // and then we compare it to epsilon (1e-8) 
    // If y (or 1-y) is smaller than epsilon we round strnum 
    if (y<epsilon || (1-y)<epsilon) { 
     strnum = x.toExponential(10); 
    } 

    //and if it isn't, strnum is returned as normal 
    return strnum; 
} 

如果你感興趣的功能的實際展示,你可以看看我做的一個計算器(它是用JavaScript編寫的,所以你可以輕鬆地檢查代碼)。鏈接是:http://www.periodni.com/calculator.html

這是我做到這一點的方式,但是我的實際問題是:有人知道有更好的方法嗎?

+3

*「我試圖在JavaScript的eval刪除此舍入誤差()函數,而不會影響結果的準確性」 *'eval'無關,用它做,它只是IEEE-754雙精度浮點數不能完美地表示每個值。 –

回答

0

只需使用toFixed(2)像:

var rounded = originalvar.toFixed(2); 
相關問題