我们如何在golang中将float64类型截断为特定的精度? [英] How can we truncate float64 type to a particular precision in golang?

查看:643
本文介绍了我们如何在golang中将float64类型截断为特定的精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


fmt
strconv


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

我不得不写上面的程序将float64变量的精度降低到2.
在这种情况下,我同时使用了strconv和fmt。有没有其他的逻辑方法可以做到这一点?

解决方案

你不需要任何额外的代码...它的就像

  import(
fmt


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

测试代码


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 ?

解决方案

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

这篇关于我们如何在golang中将float64类型截断为特定的精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆