gpt4 book ai didi

go - 如何用逗号和 2 位小数格式化货币?

转载 作者:IT王子 更新时间:2023-10-29 01:13:45 25 4
gpt4 key购买 nike

我正在尝试将一些数字格式化为货币,使用逗号和 2 位小数。我为逗号找到了“github.com/dustin/go-humanize”,但它不允许指定小数位数。 fmt.Sprintf 将进行货币和小数格式化,但不会进行逗号。

for _, fl := range []float64{123456.789, 123456.0, 123456.0100} {
log.Println(humanize.Commaf(fl))
}

结果:

123,456.789
123,456
123,456.01

我期待:

$123,456.79
$123,456.00
$123,456.01

最佳答案

这就是 humanize.FormatFloat() 所做的:

// FormatFloat produces a formatted number as string based on the following user-specified criteria:
// * thousands separator
// * decimal separator
// * decimal precision

在你的情况下:

FormatFloat("$#,###.##", afloat)

正如 commentedLenW 所说,float ( in Go, float64 ) 不适合货币。
参见 floating-point-gui.de

使用像 go-inf/inf 这样的包(以前是 go/dec,例如在 this currency implementation 中使用)会更好。

参见 Dec.go:

// A Dec represents a signed arbitrary-precision decimal.
// It is a combination of a sign, an arbitrary-precision integer coefficient
// value, and a signed fixed-precision exponent value.
// The sign and the coefficient value are handled together as a signed value
// and referred to as the unscaled value.

Dec 类型确实包含 a Format() method


自 2015 年 7 月以来,您现在拥有来自 leekchan/accounting Kyoung-chan Lee (leekchan) ,其中包含相同的建议:

Please do not use float64 to count money. Floats can have errors when you perform operations on them.
Using big.Rat (< Go 1.5) or big.Float (>= Go 1.5) is highly recommended. (accounting supports float64, but it is just for convenience.)

fmt.Println(ac.FormatMoneyBigFloat(big.NewFloat(123456789.213123))) // "$123,456,789.21"

关于go - 如何用逗号和 2 位小数格式化货币?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31503742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com