简体   繁体   中英

Format a decimal to remove trailing zeros and have a thousandths separator

I have currently code that calculates decimal values based on SQL query summation. I would like this value to be formatted in such a way that it has 2 decimal places when needed, and 0 when it is a whole number. In addition to this, I also want to keep a thousandths separator.

Example:

 string value1 = "1234.00"
 string value2 = "1234.56"

//my goal
//parsed = 1,234
//parsed2 = 1,234.56

I have tried a number of variations of formatting with no luck. What is the proper syntax for this?

Huge thanks in advance.

The first thing to note is that you cant format strings as numbers correctly, they have to be numeric types. You can use double.TryParse / double.Parse to make numeric types from a string if need be.

But the format you're looking for is #,000.##

var value1 = 1234.00;
var value2 = 1234.56;
var format = "#,###.##";
Console.WriteLine(value1.ToString(format)); // 1,234
Console.WriteLine(value2.ToString(format)); //1,234.56

Live example: https://do.netfiddle.net/YoYcP0

Full details of custom numeric format strings and standard numeric format strings

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