简体   繁体   English

为什么 Node.js 会自动舍入我的浮点数?

[英]Why is Node.js automatically rounding my floating point?

I'm trying to write a function that would fetch me the number of decimal places after the decimal point in a floating-point literal using the answer as a reference from here .我正在尝试编写一个 function ,它将使用此处的答案作为参考来获取浮点文字中小数点后的小数位数。

Although this seems to work fine when tried in the browser consoles, in the Node.js environment while running test cases, the precision is truncated only up to 14 digits.尽管在浏览器控制台中尝试这似乎工作正常,但在 Node.js 环境中运行测试用例时,精度仅被截断至 14 位。

let data = 123.834756380650877834678
console.log(data) // 123.83475638065088

And the function returns 14 as the answer. function 返回 14 作为答案。

Why is the rounding off happening at rest?为什么在 rest 发生舍入? Is it a default behavior?这是默认行为吗?

The floating-point format used in JavaScript (and presumably Node.js) is IEEE-754 binary64. JavaScript(可能是 Node.js)中使用的浮点格式是 IEEE-754 binary64。 When 123.834756380650877834678 is used in source code, it is converted to the nearest representable value, which is 123.834756380650873097692965529859066009521484375.源代码中使用123.834756380650877834678时,将其转换为最接近的可表示值,即 123.834756380650873097692965529859066009521484375。

When this is converted to a string with default formatting, JavaScript uses just enough digits to uniquely distinguish the value .将其转换为具有默认格式的字符串时, JavaScript 使用足够的数字来唯一区分 value For 123.834756380650873097692965529859066009521484375, this should produce “123.83475638065087”.对于 123.834756380650873097692965529859066009521484375,这应该产生“123.83475638065087”。 If you are getting “123.83475638065088”, which differs in the last digit, then the software you are using does not conform to the JavaScript specification (ECMAScript).如果您收到“123.83475638065088”,最后一位不同,那么您使用的软件不符合 JavaScript 规范 (ECMAScript)。

In any case, the binary64 format does not have sufficient precision to preserve the information that the original numeral, “123.834756380650877834678”, has 21 digits after the decimal point.在任何情况下,binary64 格式都没有足够的精度来保留原始数字“123.834756380650877834678”在小数点后有 21 位的信息。

The code you link to also does not and cannot compute the number of digits in an original numeral.您链接到的代码也不会也无法计算原始数字中的位数。 It computes the number of digits needed to uniquely distinguish the value represented after conversion to binary64.它计算唯一区分转换为 binary64 后表示的值所需的位数。 For sufficiently short numerals without trailing zeros after the decimal point, this is the same as the number of digits after the decimal point in the original numeral.对于足够短的数字,小数点后没有尾随零,这与原始数字中小数点后的位数相同。 For others, it may not be.对于其他人来说,可能不是。

it is default behavior of JavaScript.I think it will be same in node.js.这是 JavaScript 的默认行为。我认为它在 node.js 中会相同。

in JS The maximum number of decimals is 17.在 JS 中的最大小数位数是 17。

for more details take a look at here有关更多详细信息,请查看此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM