Javascript parseFloat '1.23e-7' 在需要 0.000000123 时给出 1.23e-7

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4126206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:27:00  来源:igfitidea点击:

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

javascriptscientific-notationparsefloat

提问by shanesolo

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 wide range of floating-point numbers, some represented in scientific notation.

我正在对包含各种浮点数的表列进行排序,其中一些以科学计数法表示。

I am using the jQuery tablesorter2.0 plugin which is using 'parseFloat' for cells that start with a digit. The issue is that parseFloat returns very small numbers represented as 1.23e-7 as a string and is not expanding this to 0.000000123. As a result tablesorter sorts the content of the column as text instead of numerics.

我正在使用 jQuery tablesorter2.0 插件,该插件对以数字开头的单元格使用“parseFloat”。问题是 parseFloat 返回非常小的数字,表示为 1.23e-7 作为字符串,并且没有将其扩展为 0.000000123。结果,tablesorter 将列的内容作为文本而不是数字进行排序。

**Column To Sort**
2.34
1.01
13.56
1.23e-7

**After Sort Now**
1.01
1.23e-7
13.56
2.34

**Expect**
1.23e-7
1.01
2.34
13.56
**Column To Sort**
2.34
1.01
13.56
1.23e-7

**After Sort Now**
1.01
1.23e-7
13.56
2.34

**Expect**
1.23e-7
1.01
2.34
13.56

Is there an efficient way of representing very small scientific notation numbers as expanded floating-point numbers?

是否有一种有效的方法可以将非常小的科学记数法数字表示为扩展的浮点数?

Solution:

解决方案:

tablesorter determines how to sort a column based on the first of tablesorters automatic parsers to return true for the content of a cell in that column. If the cell contained 1.23e-7 than it defaulted to sort by text because the 'digit' parser does not interpret this as a number.

tablesorter 确定如何根据 tablesorters 自动解析器中的第一个对列进行排序,以对该列中的单元格内容返回 true。如果单元格包含 1.23e-7,则它默认按文本排序,因为“数字”解析器不会将其解释为数字。

So to workaround, the following code represents the scientific notation number as a string that tablesorter can interpret/parse as a digit and so ensures numerical sorting on the column. @bitplitter - thanks for the toFixed() tip.

因此,要解决此问题,以下代码将科学记数法数字表示为一个字符串,tablesorter 可以将其解释/解析为数字,从而确保对列进行数字排序。@bitplitter - 感谢 toFixed() 提示。

var s = "1.23e-7";
// Handle exponential numbers.
if (s.match(/^[-+]?[1-9]\.[0-9]+e[-]?[1-9][0-9]*$/)) {
  s = (+s).toFixed(getPrecision(s));
}
//returns 0.000000123

// Get a nice decimal place precision for the scientific notation number.
// e.g. 1.23e-7 yields 7+2 places after the decimal point
// e.g. 4.5678e-11 yields 11+4 places after the decimal point
function getPrecision(scinum) {
  var arr = new Array();
  // Get the exponent after 'e', make it absolute.  
  arr = scinum.split('e');
  var exponent = Math.abs(arr[1]);

  // Add to it the number of digits between the '.' and the 'e'
  // to give our required precision.
  var precision = new Number(exponent);
  arr = arr[0].split('.');
  precision += arr[1].length;

  return precision;
}

采纳答案by posdef

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 codeand the regex given by JasonS on another question.

即使 OP 已经发布了他的解决方案,我还是想分享一个我偶然发现的相当简单的解决方案,它基于 tablesorter源代码中的解析器和 JasonS 在另一个问题上给出的正则表达式。

// 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.

它适用于我的表格,几乎所有值都以科学记数法给出。它自动检测(is:零件)并正确排序多个字段。希望它可以帮助其他可能偶然发现这个问题的人。

回答by Bitsplitter

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

您可以使用toFixed()而不是parseFloat()按照您想要的方式格式化数字。例如(1.23e-7).toFixed(9)将呈现为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.

为了能够使用 sorts 默认字符串比较对它们进行排序,请确保在所有这些字符串前加上零,并使它们的大小相同,以便小数点对齐。

You can extend the string object with padLeft like this:

您可以像这样使用 padLeft 扩展字符串对象:

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')

现在你可以打电话 ((1.23e-7).toFixed(9)).padLeft(15,'0')

回答by user187291

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

问题不是 parseFloat,而是默认情况下使用字符串比较的排序。尝试强制执行数字比较:

a.sort(function(x, y) { return x - y })