thinkeridea / go-extend

go语言扩展包,收集一些常用的操作函数,辅助更快的完成开发工作,并减少重复代码

Home Page:https://pkg.go.dev/github.com/thinkeridea/go-extend

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

四舍五入函数存在精度问题

GlowingRuby opened this issue · comments

https://github.com/thinkeridea/go-extend/blob/main/exmath/round.go
四舍五入函数存在精度问题,如0.565保留两位小数输出的是0.56而不是0.57

你可能需要了解一些关于浮点数的基础知识,以下是我找到的一些资料:

https://en.wikipedia.org/wiki/IEEE_754
https://grouper.ieee.org/groups/msc/ANSI_IEEE-Std-754-2019/background/
http://c.biancheng.net/view/314.html

当前函数受浮点数算法影响,无法做到绝对的精准(浮点数本身精度并不高),只是比现有社区其它版本有所改善(精度、性能、api使用简便性),浮点数无法对精度做出保证,在较重要的数值上(例如货币)请使用更小的单位例如分进行存储和计算,展示时转换为浮点数就行展示