Custodio
Custodio

Reputation: 8954

Format decimal localizated and formated

The example explains the question

expected : 17,590

First try:

const decimal value = 17.59m;
const string format = "{0:0,000}";
var result = string.Format(format, value);

This will result 0,018 of course because the culture is en-US and , is interpreted as thousand separator.

Second try:

const decimal value = 17.59m;
var result = Convert.ToString(value, CultureInfo.GetCultureInfo("pt-BR"));

Now I get 17,59

How can I merge format and localization using asp.net framework features?

Upvotes: 1

Views: 289

Answers (1)

Oded
Oded

Reputation: 499312

You can call ToString directly on the decimal value - it has overloads that take format strings and a CultureInfo object.

Note that in a numeric format string the decimal separator is represented as a . (which will get converted to the appropriate decimal separator).

This:

var result = 17.59m.ToString("0.000", CultureInfo.GetCultureInfo("pt-BR"));

Produces:

17,590

Upvotes: 2

Related Questions