From a1f37b9051314356b623d845b233f20dca5fb50f Mon Sep 17 00:00:00 2001 From: charlie <3140647@qq.com> Date: Tue, 29 Mar 2022 23:17:37 +0800 Subject: [PATCH] fen and yuan --- currency/amountConvert.go | 15 +++++++++++- currency/amountConvert_test.go | 42 ++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/currency/amountConvert.go b/currency/amountConvert.go index dcd9c9e..a0d2a3b 100644 --- a/currency/amountConvert.go +++ b/currency/amountConvert.go @@ -4,6 +4,7 @@ import ( "strconv" "github.com/shopspring/decimal" + "golang.org/x/exp/constraints" ) // @title 分转换为元 @@ -19,7 +20,6 @@ func CentToDollar(cent int32) string { // 元转换为分 func DollarToCent(dollar string) int64 { - p, _ := strconv.ParseFloat(dollar, 64) d := decimal.New(1, 2) @@ -27,3 +27,16 @@ func DollarToCent(dollar string) int64 { return df } + +func FenToYuan[T constraints.Integer](v T) string { + d := decimal.New(1, 2) + + return decimal.NewFromInt(int64(v)).DivRound(d, 2).StringFixedBank(2) +} + +func YuanToFen(yuan string) int64 { + p, _ := decimal.NewFromString(yuan) + + d := decimal.New(1, 2) + return p.Mul(d).IntPart() +} diff --git a/currency/amountConvert_test.go b/currency/amountConvert_test.go index 9f7e60c..e9c43ec 100644 --- a/currency/amountConvert_test.go +++ b/currency/amountConvert_test.go @@ -45,3 +45,45 @@ func TestDollarToCent(t *testing.T) { } } } + +func TestYuanToFen(t *testing.T) { + cases := []struct { + dollar string + excepted int64 + }{ + {"240.40", 24040}, + {"999999.40", 99999940}, + {"999.99", 99999}, + {"0.01", 1}, + {"999999.01", 99999901}, + {"1000000.99", 100000099}, + } + + for _, c := range cases { + result := YuanToFen(c.dollar) + if result != c.excepted { + t.Fatalf("dollar to cent failed, dollar:%s execpted:%d result:%d", c.dollar, c.excepted, result) + } + } +} + +func TestFenToYuan(t *testing.T) { + cases := []struct { + cent int + excepted string + }{ + {24040, "240.40"}, + {99999940, "999999.40"}, + {99999, "999.99"}, + {1, "0.01"}, + {99999901, "999999.01"}, + {100000099, "1000000.99"}, + } + + for _, c := range cases { + result := FenToYuan(c.cent) + if result != c.excepted { + t.Fatalf("dollar to cent failed, dollar:%d execpted:%s result:%s", c.cent, c.excepted, result) + } + } +}