light-core/util/amount.go
2024-12-18 03:08:49 +08:00

38 lines
1.3 KiB
Go
Raw Permalink 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 util
import (
"github.com/shopspring/decimal"
"strings"
)
func Fen2Yuan(price int64) string {
d := decimal.New(1, 2) //分除以100得到元
result := decimal.NewFromInt(int64(price)).DivRound(d, 2).String()
//fmt.Printf("输入值为:%d, 分转元后,精度为二的结果为:%s\n", price, result)
return result
}
func FenToYuan00(price int64) string {
d := decimal.New(1, 2) //分除以100得到元
result := decimal.NewFromInt(int64(price)).DivRound(d, 2).String()
if find := strings.Contains(result, "."); find {
return result
} else {
return result + ".00"
}
}
// 元转分,乘以100后保留整数部分
func Yuan2Fen(price float64) int64 {
d := decimal.New(1, 2) //分转元乘以100
d1 := decimal.New(1, 0) //乘完之后保留2为小数需要这么一个中间参数
//df := decimal.NewFromFloat(price).Mul(d).DivRound(d1,2).String()
//df := decimal.NewFromFloat(price).Mul(d).IntPart()
//如下是满足当乘以100后仍然有小数位取四舍五入法后再取整数部分
dff := decimal.NewFromFloat(price).Mul(d).DivRound(d1, 0).IntPart()
//fmt.Printf("输入值为:%f, 简单的元转分后,取整数部分:%d\n", price, df)
//fmt.Printf("输入值为:%f, 元转分后,若还有小数,需做四舍五入后,再取整数:%d\n", price, dff)
return dff
}