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

1

14

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

Biota answered 9/5, 2013 at 16:32 Comment(5)
What exactly are you passing in for the value? String.Format("{0:#,#.000}", 1256) prints "1,256.000". I think we need to see more of your code.Dorman
See edit. Sorry about that.Biota
Based on your edit, it looks like you're now dividing the input by 1000. As you state, the f3 format should give you exactly what you need at this point.Dorman
value.ToString("F3")Flaring
@Flaring That does 3 decimal places but no thousands separators.Santinasantini
B
21

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.

Biota answered 16/5, 2013 at 14:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.