sha*_*olo 9 javascript scientific-notation parsefloat
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将列的内容排序为文本而不是数字.
Run Code Online (Sandbox Code Playgroud)**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而不是默认按文本排序,因为'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;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用toFixed()
而不是parseFloat()
按照您希望的方式格式化数字.例如,(1.23e-7).toFixed(9)
将呈现为0.000000123
为了能够使用排序默认字符串比较对这些进行排序,请确保为它们添加前缀为零,并使它们具有相同的大小,以便小数点排成一行.
您可以使用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;
}
Run Code Online (Sandbox Code Playgroud)
现在你可以打电话了 ((1.23e-7).toFixed(9)).padLeft(15,'0')
虽然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'
});
Run Code Online (Sandbox Code Playgroud)
它适用于我的桌子,几乎所有的值都用科学记数法给出.它会自动检测(is:
部件)并正确排序多个字段.希望它可以帮助那些可能偶然发现这个问题的人.