在 JavaScript 中使用科学记数法的陷阱

Pitfalls with using scientific notation in JavaScript

这个问题不是寻求开发者代码格式化的意见。就个人而言,我更喜欢在我的 JS 代码中使用科学记数法,因为我相信它更具可读性。对我来说,6e8600000000 更具可读性。话虽如此,我只是在寻找在 JS 中以科学记数法指定数字的潜在风险和缺点。我不经常在野外看到它,想知道是否有技术原因,或者仅仅是因为开发人员的要求。

来自 this 问题中的 O.R.Mapper:

Human users are not the only ones who want to read numbers. It seems D3 will throw an exception when encountering a translate transformation that contains coordinates in scientific notation

此外,如果您想要更改字符串表示形式,而不是仅仅更改源代码中的文字形式,则必须小心 serialized/stored 数据。

此外,根据经验,您通常可以拥有大量数字,其重要性体现在各个数字上,例如 ID 或 phone 号码。在这种情况下,将这些数字简化为科学记数法会损害可读性。

你看不到科学记数法 "often in the wild" 因为在 JS 中实际输入的唯一数字往往是常量:

  • 以代码为中心的常量(例如枚举和级别)往往很小。
  • Physical/mathematical 常量(例如 π 或 e)往往具有高度特异性。

这些都没有从科学记数法中获益太多。

我看到 Plank's constant 'in the wild' 为:

const h = 6.62607004e-34;
console.log('Plank', h);

另一个经常有意义的地方是时间限制,例如一天中的毫秒数 864e5。例如:

function addDaysToDate(date, days) {
  if (days === 0)
    return date;
  date.setTime(864e5 * days + date.valueOf());
  return date;
}

const now = new Date();
const thisTimeTomorrow = addDaysToDate(now, 1);
console.log('This time tomorrow', thisTimeTomorrow);

我认为没有任何技术原因不使用这种表示法,更多的是开发人员根本避免硬编码数字。

我认为没有任何风险。您可能必须小心字符串中的数字,但如果您这样做,那么此语法的问题远小于数字本地化(例如,DE 用户输入 "20.000,00",期望 2e4,但得到 2e6 由于不变的数字格式交换千位和小数点分隔符)。

我要补充一点,对于小数字,JS 无论如何都会默认输出该语法,但在一定程度上避免大数字(因浏览器而异):

console.log('Very small', 1234 / 100000000000)
console.log('Large, but still full in some browsers', 1e17 * 1234)
console.log('Large, scientific', 1e35 * 1234)

E-notation indicates a number that should be multiplied by 10 raised to a given power.

不是科学的指数计数法。一个陷阱是 e "times ten raised to the power of" in JavaScript is not The number e the base of the natural logarithm, represented at browser as Math.E. For individuals familiar with the mathematical constant e、JavaScript e 具有完全不同的含义。 6 * Math.pow(10, 8) returns 预期结果,不包括使用 JavaScript 工件 e

Although the E stands for exponent, the notation is usually referred to as (scientific) E-notation rather than (scientific) exponential notation. The use of E-notation facilitates data entry and readability in textual communication since it minimizes keystrokes, avoids reduced font sizes and provides a simpler and more concise display, but it is not encouraged in publications. Submission Guidelines for Authors: HPS 2010 Midyear Proceedings