From the source below, I want to get float type result 33.33
. If use fmt.Sprintf("%.2f", v)
can work well. But want to get the result in the floatTest
function. How to do?
func main() {
v := floatTest(30, 90)
fmt.Println(v)
// 33.33333333333333
vv := fmt.Sprintf("%.2f", v)
fmt.Println(vv)
// 33.33
}
func floatTest(count float64, total float64) float64 {
return (count / total * 100)
}
Multiply by 100; truncate via int
conversion; convert back to float32 and divide by 100:
func precision2(f float64) float64 {
return float64(int(f*100)) / 100
}
https://play.golang.org/p/jbsdeQKgJji
This link has examples using the math
package - but I generally try to avoid including packages for trivial operations.