Kamal
Kamal

Reputation: 2522

c# string format issue for money

I need to convert a string to a monetary format of {###}.###.###,##

that is

a value of 5461497702600

would become

54.614.977.026,00

The numbers become excessively large.

I am using

return string.Format("{0:#" + (val < 1000 ? "" : "\\.") + "##0.00}", val);

which returns for the example

54614977.026,00

(only one dot)

Any help would be appreciated

Upvotes: 2

Views: 4658

Answers (3)

LukeH
LukeH

Reputation: 269498

You can use the ToString overload that takes a format string and an IFormatProvider.

Then just use N2 as your format string and use a CultureInfo - for example, de-DE - that has . as the group separator and , as the decimal symbol:

return (val / 100).ToString("N2", new CultureInfo("de-DE"));

Beware, if val is an integer type rather than a floating-point type then dividing by 100 will lose the two least significant digits. To avoid this you can convert the integer value to a decimal when dividing:

return (val / 100M).ToString("N2", new CultureInfo("de-DE"));

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273484

It is simpler than you seem to think, just use:

   decimal number = 5461497702600M;
   string s = string.Format("{0:#,##0.00}", number );

It is essential to use decimal here. The #,##0.00 picture is a very standard way of doing this, the output will use the system default symbols and the fromatter is smart enough to repeat the 3 digit grouping as needed. Use the following overload to specify a Culture, this example with the InvariantCulture will always use a decimal point:

 string s = string.Format(System.Globalization.CultureInfo.InvariantCulture, 
      "{0:#,##0.00}", number);

Upvotes: 5

A9S6
A9S6

Reputation: 6675

I think what you are trying to do depends on the current culture/regional settings of your machine. In your case, you are trying to use a COMMA as decimal and a decimal as COMMA, thousand's separator

Upvotes: 0

Related Questions