四舍五入到Golang中的所有小数点 [英] Round all decimal points in Golang
问题描述
我试图以非常规方式将float64变量中的所有数字四舍五入.例如:
I'm trying to unconventionally round all the digits in a float64 variable. For example:
3.4444445-> 3.5
3.4444445 --> 3.5
我想做到这一点而不将其转换为字符串!
I want to do this without converting it into a string!
推荐答案
Golang的数学库提供了 Round
函数.但是,它将float64舍入为一个int,这意味着会丢失小数.
Golang's math library provides a Round
function. However, it rounds the float64 to an int, meaning decimals are lost.
对此的快速解决方法是将数字乘以要保存的小数位数,然后四舍五入,然后再除以:
A quick workaround around this would be to multiple the number by the number of decimals you want to save, then round, then divide it back again:
raw := 4.335
rounded := math.Round(raw * 10) / 10
会给您想要的结果.
您可能想要创建一个小助手功能来舍入保存任意数量的数字:
You may want to create a little helper function to round saving any number of digits:
func roundTo(n float64, decimals uint32) float64 {
return math.Round(n*math.Pow(10, float64(decimals))) / math.Pow(10, float64(decimals))
}
用法:
roundTo(4.2655, 1) // 4.3
roundTo(4.3454, 3) // 4.345
这篇关于四舍五入到Golang中的所有小数点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!