go中使用decimal需要使用第三方库,一般使用github.com/shopspring/decimal
但是在实际使用中,会出现当decimal为整数时(如 48.00),调用本身接口转换成string时,无效的0会被省略。
price, _ := decimal.NewFromString("48.00")
fmt.Println(price.String())
结果:48
当我们需要显示为金额时,需要额外处理让其显示小数点后面的0,即当小数点后的0被忽略时,自行填充。
实现上面的要求,可以使用StringFixed
进行格式化:
StringFixed()可以保留小数点后指定位数
func Test_StringFixed(t *testing.T) {
amount1, _ := decimal.NewFromString("300012.2834")
t.Log(amount1.StringFixed(4))
amount2, _ := decimal.NewFromString("300012.2834")
t.Log(amount2.StringFixed(3))
amount3, _ := decimal.NewFromString("300012.2834")
t.Log(amount3.StringFixed(2))
amount4, _ := decimal.NewFromString("300012.2834")
t.Log(amount4.StringFixed(1))
amount5, _ := decimal.NewFromString("300012.2834")
t.Log(amount5.StringFixed(0))
amount6, _ := decimal.NewFromString("300012.2834")
t.Log(amount6.StringFixed(-1))
}
示例一:
超过2位四舍五入,其余补0
Round()可以四舍五入到指定位数,直接使用StringFixed()也会自动四舍五入
func Test_Round(t *testing.T) {
amount1, _ := decimal.NewFromString("300000.2834")
t.Log(amount1.Round(2).StringFixed(2))
amount2, _ := decimal.NewFromString("300000.2864")
t.Log(amount2.Round(2).StringFixed(2))
amount3, _ := decimal.NewFromString("300000.2")
t.Log(amount3.Round(2).StringFixed(2))
amount4, _ := decimal.NewFromString("300000")
t.Log(amount4.Round(2).StringFixed(2))
t.Log("--- StringFixed ---")
amount5, _ := decimal.NewFromString("300000.2834")
t.Log(amount5.StringFixed(2))
amount6, _ := decimal.NewFromString("300000.2864")
t.Log(amount6.StringFixed(2))
amount7, _ := decimal.NewFromString("300000.2")
t.Log(amount7.StringFixed(2))
amount8, _ := decimal.NewFromString("300000")
t.Log(amount8.StringFixed(2))
}
RoundDown()可以对指定位数进行去尾
func Test_RoundDown(t *testing.T) {
amount1, _ := decimal.NewFromString("300000.2834")
t.Log(amount1.RoundDown(2).StringFixed(2))
amount2, _ := decimal.NewFromString("300000.2864")
t.Log(amount2.RoundDown(2).StringFixed(2))
amount3, _ := decimal.NewFromString("300000.2")
t.Log(amount3.RoundDown(2).StringFixed(2))
amount4, _ := decimal.NewFromString("300000")
t.Log(amount4.StringFixed(2))
}
示例三:
超过2位进一,其余补0
RoundUp()可以对指定位数进行去尾
func Test_RoundUp(t *testing.T) {
amount1, _ := decimal.NewFromString("300000.2834")
t.Log(amount1.RoundUp(2).StringFixed(2))
amount2, _ := decimal.NewFromString("300000.2864")
t.Log(amount2.RoundUp(2).StringFixed(2))
amount3, _ := decimal.NewFromString("300000.2")
t.Log(amount3.RoundUp(2).StringFixed(2))
amount4, _ := decimal.NewFromString("300000")
t.Log(amount4.RoundUp(2).StringFixed(2))
}
参考链接:
https://blog.miuyun.work
如有不对,烦请指出,感谢~