简体   繁体   English

将已经四舍五入的浮点数字符串化,然后将其转换回数字会产生进一步的精度误差吗?

[英]Would stringify an already rounded float number and then convert it back to number create further precision error?

Accrodading to Is floating point math broken? Accrodading 浮点数学被破坏了吗? , I know 0.1+0.2 results in 0.30000000000000004 instead of 0.3 because of floating point errors. ,我知道 0.1+0.2 由于浮点错误而导致 0.30000000000000004 而不是 0.3。 However, what if I copy "0.30000000000000004" from alert(0.1+0.2) and write Number("0.30000000000000004"), would it still equal to 0.1+0.2?但是,如果我从 alert(0.1+0.2) 中复制 "0.30000000000000004" 并写入 Number("0.300000000000000004") 会怎样,它仍然等于 0.1+0.2 吗?

Or in general:或者一般来说:

let a=float_number_1 + float_number2;
let b=Number((float_number_1 + float_number2).toString());

Does a always exactly equal to b? a 总是完全等于 b 吗?

Java's default conversion of a number to a string is specified to produce enough digits to uniquely distinguish the number from adjacent representable values. Java 将数字转换为字符串的默认转换被指定为生成足够的数字以唯一地将数字与相邻的可表示值区分开来 In other words, it is deliberately designed to produce a string that can be converted back to a number to produce the original value.换句话说,它被故意设计为生成一个字符串,该字符串可以转换回数字以生成原始值。

So, if you convert from a float to a string to a float or from a double to a string to a double , you will get the original number.因此,如果您从float到 string 再到float或从double到 string 再到double ,您将获得原始数字。 If you convert a double to a string to a float , you may get a different number.如果将double转换为 string 到float ,则可能会得到不同的数字。

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

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