Formatting a number with exactly two decimals in JavaScript

后端 未结 30 2287
广开言路
广开言路 2020-11-21 06:29

I have this line of code which rounds my numbers to two decimal places. But I get numbers like this: 10.8, 2.4, etc. These are not my idea of two decimal places so how I can

30条回答
  •  执念已碎
    2020-11-21 06:48

    I got some ideas from this post a few months back, but none of the answers here, nor answers from other posts/blogs could handle all the scenarios (e.g. negative numbers and some "lucky numbers" our tester found). In the end, our tester did not find any problem with this method below. Pasting a snippet of my code:

    fixPrecision: function (value) {
        var me = this,
            nan = isNaN(value),
            precision = me.decimalPrecision;
    
        if (nan || !value) {
            return nan ? '' : value;
        } else if (!me.allowDecimals || precision <= 0) {
            precision = 0;
        }
    
        //[1]
        //return parseFloat(Ext.Number.toFixed(parseFloat(value), precision));
        precision = precision || 0;
        var negMultiplier = value < 0 ? -1 : 1;
    
        //[2]
        var numWithExp = parseFloat(value + "e" + precision);
        var roundedNum = parseFloat(Math.round(Math.abs(numWithExp)) + 'e-' + precision) * negMultiplier;
        return parseFloat(roundedNum.toFixed(precision));
    },
    

    I also have code comments (sorry i forgot all the details already)...I'm posting my answer here for future reference:

    9.995 * 100 = 999.4999999999999
    Whereas 9.995e2 = 999.5
    This discrepancy causes Math.round(9.995 * 100) = 999 instead of 1000.
    Use e notation instead of multiplying /dividing by Math.Pow(10,precision).
    

提交回复
热议问题