简体   繁体   English

c#字符串格式问题

[英]c# string format issue for money

I need to convert a string to a monetary format of {###}.###.###,## 我需要将字符串转换为{###}的货币格式。###。###,##

that is 那是

a value of 5461497702600 值5461497702600

would become 会成为

54.614.977.026,00 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 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. 在此必须使用decimal 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. #,## 0.00图片是执行此操作的非常标准的方法,输出将使用系统默认符号,并且fromatter很聪明,可以根据需要重复3位分组。 Use the following overload to specify a Culture, this example with the InvariantCulture will always use a decimal point: 使用以下重载指定区域性,带有InvariantCulture的示例将始终使用小数点:

 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 . 您可以使用带格式字符串IFormatProviderToString重载

Then just use N2 as your format string and use a CultureInfo - for example, de-DE - that has . 然后,只需将N2用作格式字符串,并使用具有的CultureInfo (例如de-DE . 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. 请注意,如果val是整数类型而不是浮点类型,则除以100将丢失两个最低有效数字。 To avoid this you can convert the integer value to a decimal when dividing: 为避免这种情况,您可以在除法时将整数值转换为decimal

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 在您的情况下,您尝试将COMMA用作小数,将十进制用作COMMA,即千位分隔符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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