Reputation: 32410
Suppose I have a list of decimal numbers that I must format with a comma every three places, plus the appropriate number of digits after the decimal point. I want to use the .net string.Format
method.
I want it to work like this:
string format = ???;
string s1 = string.Format(format, "1500"); // "1,500"
string s2 = string.Format(format, "1500.25"); // "1,500.25"
string s3 = string.Format(format. "3.1415926358979"); // "3.1415926358979"
I have seen other answers where the digits after the decimal are either limited to a fixed number of digits or truncated entirely, but this doesn't work for my application. I want to add the comma-separator to the whole part of the number, but keep the digits after the decimal exactly as they are.
Upvotes: 1
Views: 2956
Reputation: 1331
The format is something like this:
string format = "{0:#,##.##################}";
Upvotes: 0
Reputation: 45155
First problem, you need to parse your strings before you can format them. There maybe some lose of precision. Then you need to decide what your maximum amount of precision you need is. Then you can do something like this:
string format = "{0:#,##0.#############}";
string s1 = string.Format(format, double.Parse("1500")); // "1,500"
string s2 = string.Format(format, double.Parse("1500.25")); // "1,500.25"
string s3 = string.Format(format, double.Parse("3.1415926358979")); // "3.1415926358979"
The #
after the decimal place is a place holder for a decimal digit. If there are no more digits it won't show trailing zeros.
If being limited to a number of decimal places or possibly losing precision when converting to double
. You could do something really cludgy like this:
public static string DecimalFormatCludge(string original)
{
var split = original.Split('.');
return string.Join(".", (new [] { int.Parse(split[0]).ToString("#,##0")}).Concat(split.Skip(1)));
}
This will split on the .
in the string, parse the first part as an int, convert it back to a string correctly formatted and then just stick the decimal part back on (if there is one)
Upvotes: 2