How can we truncate float64 type to a particular precision?

前端 未结 12 1428
礼貌的吻别
礼貌的吻别 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:20

    So after much hunting around, coming to this thread multiple times I finally found a very simple solution that allows you to control the precision of floats very simply without any weird math!

    package main
    
    import (
        "fmt"
        "github.com/shopspring/decimal"
    )
    
    func main() {
        k := 101.3874927181298723478
        p := 5
    
        v := decimal.NewFromFloat(k).Round(int32(p))
        fmt.Println(v)
    }
    // 101.38749
    

    Source: https://godoc.org/github.com/shopspring/decimal#Decimal.Round

    While I like some of the simple methods like "%.3f\n", k options, these produced a string that I would then have to convert back into a float with another strconv command that I didn't want to do.

提交回复
热议问题