Golang参数化浮点数的精度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
"fmt"
)

func main() {
f := 12.3456
fmt.Println(precision(f, 1))
fmt.Println(precision(f, 2))
fmt.Println(precision(f, 3))
// will print
// 12.3
// 12.35
// 12.346
}

func precision(f float64, p int) string {
return fmt.Sprintf("%.*f", p, f)
}