当将golang float64值与整数相乘时,由于存储浮点数的方式,结果包含高精度误差值。 这是一个代码片段,显示了我所指的问题
package main import ( "fmt" ) func main() { var l float64 = 0.2 fmt.Println("Hello, playground",l*6) }结果是
Hello, playground 1.2000000000000002这是同一个游乐场的游戏链接
是否有标准/最佳实践来解决错误?
When multiplying golang float64 values with integers the result contains high precison error values due to the way floating point numbers are stored. Here is a code snippet that shows the problem I am referring to
package main import ( "fmt" ) func main() { var l float64 = 0.2 fmt.Println("Hello, playground",l*6) }The result is
Hello, playground 1.2000000000000002Here is the play link for the same playground
Is there a standard/best practise to round of the error ?
最满意答案
这取决于用例是什么以及要显示多少位数。 你可以这样做:
func main() { var l float64 = 0.2 fmt.Printf("Hello, playground %.8f",l*6) }并且仅在小数点后显示8个单位。 但是,如果您正在处理货币,例如,您最好不要使用浮动,并将所有内容保存为美分(在美国)或数量(货币的最低面额)。
It depends what the use case is and how many digits you want to show. You could do:
func main() { var l float64 = 0.2 fmt.Printf("Hello, playground %.8f",l*6) }and only show 8 units after the decimal. But if you are dealing with currency, for example, you are better off not using floats at all, and saving everything as cents (in the US) or number of (lowest denomination of currency).
更多推荐
发布评论