How can we truncate float64 type to a particular precision?

Issue

package main

import (
    "fmt"
    "strconv"
    )

func main() {
    k := 10/3.0
    i := fmt.Sprintf("%.2f", k)
    f,_ := strconv.ParseFloat(i, 2)
    fmt.Println(f)
}

I had to write the program above to decrease the precision of a go float64 variable to 2.
In this case I was using both strconv and fmt. Is there some other logical method by which it can be done?

Solution

You don’t need any extra code … its as simple as

import (
    "fmt"
)

func main() {
    k := 10 / 3.0
    fmt.Printf("%.2f", k)
}

Test Code

Answered By – Baba

Answer Checked By – Cary Denson (GoLangFix Admin)

Leave a Reply

Your email address will not be published.