Javascript parseFloat '1.23e-7' gives 1.23e-7 when need 0.000000123

前端 未结 3 1593
梦谈多话
梦谈多话 2021-01-04 19:01
parseFloat(1.51e-6);
// returns 0.00000151

parseFloat(1.23e-7);
// returns 1.23e-7
// required 0.000000123

I am sorting table columns containing a

相关标签:
3条回答
  • 2021-01-04 19:15

    Even though the OP has posted his solution, I'd like to share a rather simpler solution I stumbled upon, which is based on the parsers in the tablesorter source code and the regex given by JasonS on another question.

    // add parser through the tablesorter addParser method 
    $.tablesorter.addParser({ 
    // set a unique id
    id: 'scinot', 
    is: function(s) { 
        return /[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/.test(s); 
    }, 
    format: function(s) { 
        return $.tablesorter.formatFloat(s);
    }, 
    type: 'numeric' 
    });
    

    It works on my tables with pretty much all values given in scientific notation. It auto-detects (the is: part) and correctly sorts multiple fields. Hope it helps others who might stumble upon this question.

    0 讨论(0)
  • 2021-01-04 19:19

    You can use toFixed() instead of parseFloat() to format the numbers the way you want. For example (1.23e-7).toFixed(9) will render as 0.000000123

    To be able to sort these with sorts default string comparison, make sure to prefix all of them with zeroes and make them all the same size so the decimal dots wil line up.

    You can extend the string object with padLeft like this:

    String.prototype.padLeft = function(len, char){
    var prefix = '';
    var length=this.length;
    if(len>length)
     for(var i=0;i < len-length;i++) prefix += char;
    return prefix + this;
    }
    

    Now you can call ((1.23e-7).toFixed(9)).padLeft(15,'0')

    0 讨论(0)
  • 2021-01-04 19:22

    the problem is not parseFloat, but sort that uses string comparison by default. Try enforcing numeric comparison:

    a.sort(function(x, y) { return x - y })
    
    0 讨论(0)
提交回复
热议问题