如何格式化带有逗号和小数点后两位的货币?

I am trying to format some numbers as a currency, with commas and 2 decimal places. I've found "github.com/dustin/go-humanize" for the commas but it doesn't allow for specifying the number of decimal places. fmt.Sprintf will do the currency and decimal formatting but not the commas.

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

Results:

123,456.789
123,456
123,456.01

I am expecting:

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

There is a good blog post about why you should never use floats to represent currency here - http://engineering.shopspring.com/2015/03/03/decimal/

From their examples you can :

  d := New(-12345, -3)
  println(d.String())

Will give you :

-12.345
fmt.Printf("%.2f", 12.3456) 

-- output is 12.34

That would be what the humanize.FormatFloat() does:

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

In your case:

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

That being said, as commented by LenW, float (in Go, float64) is not a good fit for currency.
See floating-point-gui.de.

Using a package like go-inf/inf (previously go/dec, used for instance in this currency implementation) is better.

See 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.

That type Dec does include a Format() method.


Since July 2015, you now have leekchan/accounting from Kyoung-chan Lee (leekchan) with the same advice:

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"

Try:

ToString("#,##0.00");

or you can try this too:

int number = 1234567890;
Convert.ToDecimal(number).ToString("#,##0.00");

You will get the result like this 1,234,567,890.00.