From aff81b33cd5371070e3910c19f85914a305b1d99 Mon Sep 17 00:00:00 2001 From: charlie <3140647@qq.com> Date: Sun, 27 Mar 2022 10:19:33 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=91=E9=A2=9D=E8=BD=AC=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- currency/amountConvert.go | 29 +++++++++++++++++++++ currency/amountConvert_test.go | 47 ++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 currency/amountConvert.go create mode 100644 currency/amountConvert_test.go diff --git a/currency/amountConvert.go b/currency/amountConvert.go new file mode 100644 index 0000000..dcd9c9e --- /dev/null +++ b/currency/amountConvert.go @@ -0,0 +1,29 @@ +package currency + +import ( + "strconv" + + "github.com/shopspring/decimal" +) + +// @title 分转换为元 +// @param cent 金额分 +// @return 字符串表示的元 +func CentToDollar(cent int32) string { + d := decimal.New(1, 2) + + result := decimal.NewFromInt32(cent).DivRound(d, 2).StringFixedBank(2) + + return result +} + +// 元转换为分 +func DollarToCent(dollar string) int64 { + + p, _ := strconv.ParseFloat(dollar, 64) + d := decimal.New(1, 2) + + df := decimal.NewFromFloat(p).Mul(d).IntPart() + + return df +} diff --git a/currency/amountConvert_test.go b/currency/amountConvert_test.go new file mode 100644 index 0000000..9f7e60c --- /dev/null +++ b/currency/amountConvert_test.go @@ -0,0 +1,47 @@ +package currency + +import ( + "testing" +) + +func TestCentToDollar(t *testing.T) { + cases := []struct { + cent int32 + 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 := CentToDollar(c.cent) + if result != c.excepted { + t.Fatalf("dollar to cent failed, dollar:%d execpted:%s result:%s", c.cent, c.excepted, result) + } + } +} + +func TestDollarToCent(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 := DollarToCent(c.dollar) + if result != c.excepted { + t.Fatalf("dollar to cent failed, dollar:%s execpted:%d result:%d", c.dollar, c.excepted, result) + } + } +}