How can we truncate float64 type to a particular precision?

前端 未结 12 1420
礼貌的吻别
礼貌的吻别 2021-02-02 05:33
package main

import (
    \"fmt\"
    \"strconv\"
    )

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


        
12条回答
  •  走了就别回头了
    2021-02-02 06:01

    I really don't see the point, but you could do something like this without strconv:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        untruncated := 10 / 3.0
        truncated := float64(int(untruncated * 100)) / 100
        fmt.Println(untruncated, truncated)
    }
    

提交回复
热议问题