parseFloat(1.51e-6);
// returns 0.00000151
parseFloat(1.23e-7);
// returns 1.23e-7
// required 0.000000123
我正在对包含各种科学计数法的浮点数的表格列进行排序。我使用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
有没有一种有效的方法将非常小的科学计数法数字表示为展开的浮点数?解决方案:
tablesorter 根据 tablesorter 自动解析器中第一个返回 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. 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;
}