在golang`fall64乘法上输出高精度错误的正确方法是什么?(What is the right way for rouding of high precision error on `gola

编程入门 行业动态 更新时间:2024-10-17 13:32:43
在golang`fall64乘法上输出高精度错误的正确方法是什么?(What is the right way for rouding of high precision error on `golang` float64 multiplication)

当将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.2000000000000002

Here 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).

更多推荐

本文发布于:2023-08-01 02:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1350609.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:乘法   正确   错误   方法   golang

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!