package main
import (
\"fmt\"
\"strconv\"
)
func main() {
k := 10/3.0
i := fmt.Sprintf(\"%.2f\", k)
f,_ := strconv.ParseFloat(i, 2)
fmt.Pri
No one has mentioned using math/big
. The results as pertains to the original question are the same as the accepted answer, but if you are working with floats that require a degree of precision ($money$), then you should use big.Float
.
Per the original question:
package main
import (
"math/big"
"fmt"
)
func main() {
// original question
k := 10 / 3.0
fmt.Println(big.NewFloat(k).Text('f', 2))
}
Unfortunately, you can see that .Text
does not use the defined rounding mode (otherwise this answer might be more useful), but rather always seems to round toward zero:
j := 0.045
fmt.Println(big.NewFloat(j).SetMode(big.AwayFromZero).Text('f', 2)
// out -> 0.04
Nevertheless, there are certain advantages to having your float stored as a big.Float
.