f
This commit is contained in:
@@ -1,15 +1,33 @@
|
||||
package lzUtils
|
||||
|
||||
import "fmt"
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
)
|
||||
|
||||
// RoundMoney 将金额四舍五入到指定小数位数(默认2位)
|
||||
// 所有金额计算结果都应通过此函数处理,避免浮点精度问题
|
||||
func RoundMoney(v float64, precision ...int) float64 {
|
||||
p := 2
|
||||
if len(precision) > 0 {
|
||||
p = precision[0]
|
||||
}
|
||||
factor := math.Pow10(p)
|
||||
return math.Round(v*factor) / factor
|
||||
}
|
||||
|
||||
// RoundMoney2 将金额四舍五入到2位小数并返回字符串
|
||||
// 用于需要字符串格式的场景(如 API 返回、日志打印)
|
||||
func RoundMoney2(v float64) string {
|
||||
return fmt.Sprintf("%.2f", RoundMoney(v))
|
||||
}
|
||||
|
||||
// ToWechatAmount 将金额从元转换为微信支付 SDK 需要的分(int64 类型)
|
||||
func ToWechatAmount(amount float64) int64 {
|
||||
// 将金额从元转换为分,并四舍五入
|
||||
return int64(amount*100 + 0.5)
|
||||
return int64(RoundMoney(amount)*100 + 0.5)
|
||||
}
|
||||
|
||||
// ToAlipayAmount 将金额从元转换为支付宝支付 SDK 需要的字符串格式,保留两位小数
|
||||
func ToAlipayAmount(amount float64) string {
|
||||
// 格式化为字符串,保留两位小数
|
||||
return fmt.Sprintf("%.2f", amount)
|
||||
return RoundMoney2(amount)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user