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

标签 javascript scientific-notation parsefloat

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

parseFloat(1.23e-7);
// returns 1.23e-7
// required 0.000000123

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

我正在使用 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

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

解决方案:

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;
}

最佳答案

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

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

您可以像这样使用 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;
}

现在你可以调用 ((1.23e-7).toFixed(9)).padLeft(15,'0')

关于Javascript parseFloat '1.23e-7' 在需要 0.000000123 时给出 1.23e-7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4126206/

相关文章:

javascript - 如何使用 v8 typescript 中发布的顶级异步等待

javascript - 在给定的discord channel 中搜索满足条件的所有消息并删除

javascript - .JSON 中的值的路径

c++ - c++中从double到string的转换

javascript - 如何选择合适数量的按钮

c++ - Qwt关闭轴标签的科学记数法

python - 为什么 1e400 不是一个整数?

java - 在java中将字符串转换为浮点型

javascript - 使用 parseFloat 计算丢失小数位

java - 想知道我的代码中 NumberFormat 异常背后的原因