2013-09-30 101 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); 
相关问题