保留两位小数

package main

import (
   "fmt"
   "github.com/shopspring/decimal"
)

// Decimal 四舍五入保留N位小数
func Decimal(f float64, r int32) (num float64) {
   num, _ = decimal.NewFromFloat(f).Round(r).Float64()
   return
}

func main() {
   var num float64

   num = 3.144999
   fmt.Println(Decimal(num, 2)) // 3.14

   num = 3.145000
   fmt.Println(Decimal(num, 2)) // 3.15

   num = 3.1
   fmt.Println(Decimal(num, 2)) // 3.1

   num = 3
   str := fmt.Sprintf("%.2f", num) // 小数部分位数不足右侧补零
   fmt.Println(str)                // 3.00
}

Copyright © 2024 码农人生. All Rights Reserved