【问题标题】:JavaScript: Rounding number without impacting result accuracyJavaScript:在不影响结果准确性的情况下舍入数字
【发布时间】:2023-12-24 05:30:01
【问题描述】:

问题:如果你做log1000,你会得到log1000 = 2.9999999999999996而不是3。

我尝试在不影响结果准确性的情况下消除 JavaScript eval() 函数中的此舍入错误。 在格式编号函数FormatNumber(strnum) 中,我输入了CheckEpsilon(strnum),它测试数字的“右尾”是否大于epsilon(假设epsilon 的值为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

我就是这样做的,但我的实际问题是:有谁知道这样做的更好方法吗?

【问题讨论】:

  • “我试图在不影响结果准确性的情况下消除 JavaScript eval() 函数中的这个舍入误差。” eval 与它无关,只是 IEEE -754 双精度浮点数不能完美地表示每个值。

标签: javascript numbers eval rounding floating-accuracy


【解决方案1】:

只需使用toFixed(2) 喜欢:

var rounded = originalvar.toFixed(2);

【讨论】: