golang 保留小数

发布时间:2024-07-02 22:10:24

Go语言保留小数的方法

在Go语言开发中,处理小数是非常常见的操作。在实际应用中,我们经常需要对小数进行保留指定位数的操作,如保留两位小数。

下面我将介绍几种常用的方法来保留小数:

方法一:使用strconv.FormatFloat()

Go提供了一个方便的函数strconv.FormatFloat(),可以将浮点数格式化为字符串,并指定精度。

package main

import (
    "fmt"
    "strconv"
)

func main() {
    num := 3.14159
    str := strconv.FormatFloat(num, 'f', 2, 64)
    fmt.Println(str)
}

运行以上代码,输出结果为3.14,即保留了两位小数。

方法二:使用math.Round()

另一种常用的方法是使用math.Round()函数,该函数返回离参数最近的整数值,四舍五入到0位小数。

package main

import (
    "fmt"
    "math"
)

func main() {
    num := 3.14159
    roundNum := math.Round(num*100) / 100
    fmt.Println(roundNum)
}

运行以上代码,输出结果为3.14

方法三:使用strconv.ParseFloat()

如果你需要将保留两位小数的字符串转换为浮点数,可以使用strconv.ParseFloat()函数。

package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := "3.14"
    num, _ := strconv.ParseFloat(str, 64)
    fmt.Println(num)
}

运行以上代码,输出结果为3.14

方法四:使用math.Trunc()

math.Trunc()函数可以将浮点数截断为指定位数的小数。

package main

import (
    "fmt"
    "math"
)

func main() {
    num := 3.14159
    truncNum := math.Trunc(num*100) / 100
    fmt.Println(truncNum)
}

运行以上代码,输出结果为3.14

以上就是几种常用的方法来保留小数的介绍。根据实际需求选择合适的方法,可以更高效地处理小数。

相关推荐