在 JavaScript 中获取浮点数的长度

Get float's length in JavaScript

我正在尝试获取 JavaScript 中 float 的长度,但我无法将其作为 string:

var length = ((x + '').toString().length;

因为,undefined 是一个非常规则且可能的变量值,所以我最终得到的长度是 "undefined"...

我看到了各种可能的解决方案:

首先检查 number 是否实际上是数字,然后,如果是,return 计算其字符串表示的长度:

let numbers = [undefined, null, 12345, 1.2345, '12345', '1.2345', 'abcd', '1.2345abcd', 0.1 + 0.2, 0.3, {}, []]

console.log(numbers.map(number => {
  return number === null || isNaN(number) ? 0 : number.toString().length;
}));

上面的代码片段认为 strings 实际上代表一个数字:123451.2345... 作为数字。

它将 return 0 用于 undefined、对象、数组和 null,但请注意我们需要显式检查 null,因为它可能不直观,但 isNaN(null) 将 return false。有关详细说明,请参阅 this other answer

如果你不想数.,你有多种选择:

  • 使用 String.prototype.replace().
  • 将数字的 string 表示形式中的 '.' 替换为 ''
  • 一旦你知道这个数字实际上是一个数字,检查它是否是一个 float 做 number % 1 !== 0,如果是,然后从它的 .length 中减去 1

您提到您认为 mathjs 可能是避免损害性能的最佳选择,但是完全按照您的需要执行的自定义实现可能比处理 [=75 的完整放大库更快=] 一般。

此外,您或许应该看看这个:https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil

无论如何,还有一些其他特殊情况您应该在您的自定义实现中考虑,如果您想要库可能已经正确处理,显然需要一些额外的工作。根据我的代码,您是否注意到 0.1 + 0.2 的长度? 19!怎么来的?看起来很明显 0.1 + 0.2 是 0.3,所以它的长度应该是 3。实际上,列表中的下一项是 0.3 并且它可以正常工作。

好吧,事实证明浮点数存在一些精度问题。我现在不打算谈这个,但你可以在这里阅读:https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems.

在这里你可以看到一个例子:

console.log(0.1, 0.2, 0.3, 0.1 + 0.2)

要查找浮点数的长度而不遇到未定义的问题,请使用 try、catch 和 throw。

var num = document.getElementById("num").value;
  var result = document.getElementById("result").value;
var parsedFloat;

function foo() {
  num = document.getElementById("num").value;
  result = document.getElementById("result").value;

  try {
    if (num == parseFloat(num) && num !== undefined) { // if number is equal to that number turned into a float; "1.2" becomes 1.2 and "thiswontwork" becomes NaN (not a number)
      parsedFloat = num;
      if (parsedFloat != parseInt(parsedFloat)) { // if it's a float, not an integer
        parsedFloat = parsedFloat.substring(1); // removes the last digit so that the length will be subtracted because of decimal point
      } // currently, I do not have anything for ".0".
      result = parsedFloat.length;
    } else {
      throw "Must be a number!";
    }
  } catch(err) {
    result = err;
  } finally {
    document.getElementById("result").value = result;
  }
}
<input id="num" placeholder="insert number here"><br>
<input id="result" placeholder="result">
<br>
<button onclick="foo()">Click me!</button>