- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我正在尝试将一些数字格式化为货币,使用逗号和 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)
正如 commented 的 LenW 所说,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.
Usingbig.Rat
(< Go 1.5) orbig.Float
(>= Go 1.5) is highly recommended. (accounting supportsfloat64
, 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/
我是一名优秀的程序员,十分优秀!