为什么在浮点转换中会发生这种情况?
Why this happens in floating point conversion?
我注意到一些浮点数的转换方式不同。 This question helps me about floating points however still don't know why this happens? I added two screenshots from debug mode about the sample code. Example values : 7.37 and 9.37. Encountered it in swift and surely swift uses IEEE 754 floating point standard请解释这是怎么发生的?转换如何以不同方式结束?
if let text = textField.text {
if let number = formatter.number(from: text) {
return Double(number)
}
return nil
}
Double
浮点数以2进制存储,不能精确表示所有小数。
在这种情况下,7.37和9.37被四舍五入到最接近的浮点数,分别是7.37000000000000010658141036401502788066864013671875和9.3699999999999992184029906638897953051875和9.369999999999999218402990663889795305164,=.
当然,这种十进制表示对于一般用途来说太笨重了,因此编程语言通常会打印较短的近似十进制表示。两个受欢迎的选择是
- 将正确四舍五入为原始数字的最短字符串(在本例中分别为
7.37
和 9.37
)。
- 舍入 17 位有效数字,即 is guaranteed to give the correct value when converting back to binary.
这些似乎与您看到的 2 个调试输出值相对应。
我注意到一些浮点数的转换方式不同。 This question helps me about floating points however still don't know why this happens? I added two screenshots from debug mode about the sample code. Example values : 7.37 and 9.37. Encountered it in swift and surely swift uses IEEE 754 floating point standard请解释这是怎么发生的?转换如何以不同方式结束?
if let text = textField.text {
if let number = formatter.number(from: text) {
return Double(number)
}
return nil
}
Double
浮点数以2进制存储,不能精确表示所有小数。
在这种情况下,7.37和9.37被四舍五入到最接近的浮点数,分别是7.37000000000000010658141036401502788066864013671875和9.3699999999999992184029906638897953051875和9.369999999999999218402990663889795305164,=.
当然,这种十进制表示对于一般用途来说太笨重了,因此编程语言通常会打印较短的近似十进制表示。两个受欢迎的选择是
- 将正确四舍五入为原始数字的最短字符串(在本例中分别为
7.37
和9.37
)。 - 舍入 17 位有效数字,即 is guaranteed to give the correct value when converting back to binary.
这些似乎与您看到的 2 个调试输出值相对应。