简体   繁体   中英

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

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);

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"));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM