package main
import (
\"fmt\"
\"strconv\"
)
func main() {
k := 10/3.0
i := fmt.Sprintf(\"%.2f\", k)
f,_ := strconv.ParseFloat(i, 2)
fmt.Pri
The simplest solution is numeric truncation (assuming i
is a float and you want a precision of 2 decimal points):
float64(int(i * 100)) / 100
For example:
i := 123456.789
x := float64(int(i * 100)) / 100
// x = 123456.78
If you're dealing with large numbers (numbers that can cross the max value boundaries), you should know that the above can lead to serious floating point accuracy issues:
i := float64(1<<63) // 9223372036854775808.0
fmt.Println(i, float64(int64(i * 10)) / 10)
Prints: 9.223372036854776e+18 -9.223372036854776e+17
See also: