Files
qnc-server-v3/pkg/lzkit/lzUtils/utils.go
2026-05-13 14:43:10 +08:00

34 lines
965 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package lzUtils
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(RoundMoney(amount)*100 + 0.5)
}
// ToAlipayAmount 将金额从元转换为支付宝支付 SDK 需要的字符串格式,保留两位小数
func ToAlipayAmount(amount float64) string {
return RoundMoney2(amount)
}