How can I format a currency with commas and two decimal places?

I am trying to format some digits as a currency with commas and two decimal places. I found "github.com/dustin/go-humanize" for commas, but it does not allow you to specify the number of decimal places. fmt.Sprintf will do currency and decimal formatting, but not 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 expect:

$123,456.79
$123,456.00
$123,456.01
+4
source share
4 answers

There is a good blog post about why you shouldn't use float to represent currency here - http://engineering.shopspring.com/2015/03/03/decimal/

From your examples, you can:

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

You'll get:

-12.345
+3
source

This will be what humanize.FormatFloat () does:

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

:

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

, LenW, float ( Go, float64) .
. floating-point-gui.de.

, go-inf/inf ( go/dec, , , ).

. 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() .


2015 leekchan/accounting Kyoung-chan Lee (leekchan) :

, float64 . .
big.Rat (< Go 1.5) big.Float ( >= Go 1.5). ( float64, .)

fmt.Println(ac.FormatMoneyBigFloat(big.NewFloat(123456789.213123))) // "$123,456,789.21"
+6
fmt.Printf("%.2f", 12.3456) 

- output 12.34

+1
source

Try:

ToString("#,##0.00");

and you can also try:

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

You will get a result like this 1.234.567.890.00.

-2
source

Source: https://habr.com/ru/post/1598605/


All Articles