四舍五入到Golang中的所有小数点[重复]

This question already has an answer here:

I'm trying to unconventionally round all the digits in a float64 variable. For example:

3.4444445 --> 3.5

I want to do this without converting it into a string!

</div>

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

Will give you the desired result.

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 * float64(decimals)) / float64(decimals)
}

Usage:

roundTo(4.2655, 1) // 4.3
roundTo(4.3454, 3) // 4.345