Dear all,
I would like to define a function "func Round(x float64, digits int) float64"
which rounds to the given number of digits, in the sense that I want
"strconv.FormatFloat(x,
'f', -1, 64)" to show at most the given number of digits after the decimal
point.
The following naive approach does not work:
func Round(x float64, digits int) float64 {
eps := math.Pow10(-digits)
return math.Round(x/eps) * eps
}
For example for rounding math.Pi to five digits I get "3.1415900000000003"
instead of "3.14159". https://go.dev/play/p/gRtHG6ZgTjj .
Anthropic's Claude suggested the following:
func Round(x float64, digits int) float64 {
if digits <= 0 {
pow := math.Pow10(-digits)
return math.Round(x/pow) * pow
}
format := "%." + strconv.Itoa(digits) + "f"
s := fmt.Sprintf(format, x)
result, _ := strconv.ParseFloat(s, 64)
return result
}
This seems to work, but also seems quite inefficient.
Is there a better way?
All the best,
Jochen
PS.: Here is some testing code for experimenting
https://go.dev/play/p/Xcd6fTvYend
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion visit
https://groups.google.com/d/msgid/golang-nuts/7d3ccdd4-d88b-4eba-8a36-02b51b7751e1n%40googlegroups.com.