简体   繁体   English

删除尾随零和千位分隔符(逗号)

[英]Remove trailing zeros and thousand separator (comma)

Since I am using this to remove trailing zeros when there is no value behind decimal: 由于在十进制后面没有值时,我使用它来删除尾随零:

decimal.Parse(variable).ToString("G29")

But it doesn't give thousand separator. 但这并不能给千位分隔符。 For example: 例如:

string amount = "54321.00"
string amount2 = "54321.55"
string parsed = decimal.Parse(amount).ToString("G29");
string parsed2 = decimal.Parse(amount2).ToString("G29");
//parsed = 54321
//parsed2 = 54321.55

//my goal
//parsed = 54,321
//parsed2 = 54,321.55

Is there any better format type? 有没有更好的格式类型?

Use a custom format 使用自定义格式

string format = "#,#.##";

decimal noDecimalPlaces = 54321.00m;
decimal decimalPlaces = 54321.55m;

Console.WriteLine(noDecimalPlaces.ToString(format)); // writes 54,321
Console.WriteLine(decimalPlaces.ToString(format)); // writes 54,321.55

You can read more about formatting decimals on msdn . 您可以在msdn上阅读有关格式化小数的更多信息。

The way this works 工作方式

The latter part .## specifies that you allow up to two decimal places. 后一部分.##指定最多允许两位小数。 The former part #,# specifies that you want to separate the integer part of your value. 前一部分#,#指定您要分隔值的整数部分。

Note : 注意事项

The number formatting is still culture specific , so for cultures that use , as the decimal separator and . 数字格式尚文化相关的 ,所以对于使用文化,作为小数点分隔符和. for digit grouping your numbers will be displayed as 54.321 and 54.321,55 instead. 对于数字分组,您的号码将显示为54.32154.321,55 You can find out more about formatting in .NET here . 您可以在此处找到有关.NET格式的更多信息。

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

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