Home > front end >  Format a decimal to remove trailing zeros and have a thousandths separator
Format a decimal to remove trailing zeros and have a thousandths separator

Time:10-06

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.

CodePudding user response:

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://dotnetfiddle.net/YoYcP0

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

  •  Tags:  
  • c#
  • Related