views:

351

answers:

3

Hi guys

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

A: 

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

A9S6
Yes, agreed. However we are using a cultural setting that is reqiured for the rest of the system that does not support this country monetary format. So I need to do it programatically.
Kamal
+2  A: 

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);
Henk Holterman
That...is...awesome. Thanks. Out of curiosity, when you say it is essential to use decimal...why? and what will happen if I try it with a double? That's the two types I potentially have, although I think I am using decimal throughout.
Kamal
@Kamal, if you use double you will see rounding errors in the last digits (much sooner than with decimal). For money, use decimal. Note the 'M' suffix.
Henk Holterman
A small nitpick: This will format the number as `5.461.497.702.600,00` while the question specifies that it should be `54.614.977.026,00`. Just divide the number by 100 before applying the formatting.
LukeH
@Luke, good catch, but indeed easy to fix.
Henk Holterman
+1  A: 

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"));
LukeH
+1 Also very clean solution.
Kamal