format number with 3 trailing decimal places, a decimal thousands separator, and commas after that

Brett picture Brett · May 9, 2013 · Viewed 25.4k times · Source

This is probably a simple question, and I'm sure there's a way to do it with string.format(), NumberFormatInfo, CultureInfo or some combination of them, but I need to display large numeric values with 3 trailing decimal places, a decimal instead of a comma for the thousands separator, and then a comma for the millions separator and up.

The input is either a whole number or a number followed by up to three decimal places (20000, 123.456, 12.2)

For example:

142650 should display as 142,650.000

11200.50 should display as 11,200.500

123.456 should remain 123.456

I suppose it's the same as dividing the value by 1000 and then using string.format("{0:f3}", value), but I was hoping to find something that didn't take arithmetic.

String.Format("{0:#,#.000}", value) gets me close, but it puts a leading 0 on small numbers, so 1.256 is displaying as 01.256, when I need it to remain just 1.256

Answer

Brett picture Brett · May 16, 2013

The format String.Format("{0:#,0.000}", value) ended up doing it for me. It works for whole numbers and numbers with anywhere from 1 to 3 trailing decimal places.