我是 Golang 的新手。我想将 float 分成整数和小数部分。经过一些研究,我实现了它,但我的代码中存在问题。我使用 5.8 作为输入,但结果是 5 和 0.79999。
package main
import(
"fmt"
"math"
)
func Round2(val float64) {
intpart, div := math.Modf(val)
fmt.Println(div)
fmt.Println(intpart)
}
func main() {
fmt.Println("Hello, playground")
Round2(5.8)
}
我已经试过了,我得到的输出是:
0.7999999999999998
5
如果有任何其他方法可以做到这一点,请告诉我。 我已经插入了带有我的代码的 go playground。
最佳答案
这是浮点运算的神器。浮点值并不总是与您期望的值完全相同,因为并非所有数字都可以用您碰巧使用的任何处理器所使用的浮点格式准确表示。显然,该值非常接近 0.8,等于 15 位有效数字。请注意,这并非特定于 Go。
代替
fmt.Println(div)
尝试
fmt.Printf(".4f\n", div) // shows only 4 decimal places
看起来这篇文章有一些很好的信息:https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
关于go - 使用golang分隔整数和小数部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40143750/