duanlang1196 2018-11-29 04:21
浏览 552
已采纳

如何在GO中将float64值修整为特定的小数点? [重复]

This question already has an answer here:

I want to trim latitude and longitude of address upto 5 decimal points. latitude and longitude are of type float64 I have created a function round the value. My function is like this::

func DoubleRoundFive(val float64) float64 {
    formattedVal := fmt.Sprintf("%.5f", val)
    roundedVal, _ := strconv.ParseFloat(formattedVal, 64)
    return roundedVal
}

Output and usage::

DoubleRoundFive(76.70289609999999)

Output::

76.7029

But I just want to trim the value upto 5 decimal points. I want output as 76.70289 . Is it possible in GO?? I want exact 5 decimal values because I am using this for latitude longitude. This is a GO playground Link

</div>
  • 写回答

1条回答 默认 最新

  • doucheng1063 2018-11-29 04:49
    关注

    Try this:

    package main
    
    import (
        "fmt"
    
    )
    
    func main() {
        val := DoubleRoundFive(76.70289609999999)
        fmt.Println(val)
    }
    
    func DoubleRoundFive(val float64) float64 {
        valInt := int64(val*100000)
        val = float64(valInt)/100000
        return val
    }
    

    Go Playground: https://play.golang.org/p/O_H_buvJtDO

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?