HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

How can we truncate float64 type to a particular precision?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
truncatehowfloat64cantypeprecisionparticular

Problem

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

Code Snippets

import (
    "fmt"
)

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

Context

Stack Overflow Q#18390266, score: 102

Revisions (0)

No revisions yet.