简体   繁体   中英

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 .

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. You can find out more about formatting in .NET here .

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