小编sha*_*olo的帖子

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

parseFloat(1.51e-6);
// returns 0.00000151

parseFloat(1.23e-7);
// returns 1.23e-7
// required 0.000000123
Run Code Online (Sandbox Code Playgroud)

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

我正在使用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
Run Code Online (Sandbox Code Playgroud)

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

解:

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

因此,要解决此问题,以下代码将科学记数法编号表示为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. …
Run Code Online (Sandbox Code Playgroud)

javascript scientific-notation parsefloat

9
推荐指数
2
解决办法
2万
查看次数