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 确定如何根据第一个 tablesorters 自动解析器对列进行排序,以对该列中单元格的内容返回 true。如果单元格包含 1.23e-7,则默认按文本排序,因为“数字”解析器不会将其解释为数字。
因此,作为解决方法,以下代码将科学记数法数字表示为 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;
}