I am trying to get user input, parse it and then display with String.Format(), formatting thousands with comas.
So, if user provides
1000 I will display 1,000
1000.00 => 1,000.00
1000.0 => 1,000.0
1,000.5 => 1,000.5
Basically I want to keep all decimals(including trailing zeroes) that were provided and just add formatting for thousands. I tried:
String.Format("{0:#,0.######}" , Decimal.Parse(input));
String.Format("{0:#,0.######}" , Double.Parse(input);
double.Parse(input)
is a no go, asdouble
does not keep track of the number of decimals.decimal.Parse(input).ToString()
will show thatdecimal
does keep track of that. Unfortunately,decimal.Parse(input).ToString()
uses this precision and doesn't use a thousands separator, anddecimal.Parse(input).ToString("N")
ignores the precision but does use a thousands separator.Manually extracting the precision from the decimal works though, and that allows you to build the correct format string:
This is based on the layout of
decimal
as described on MSDN:See it working on .NET Fiddle. (courtesy of @Alisson)
You can use regex for this:
If you don't mind 1000 converted to 1,000.00 then following is the best as it considers user's locale too.
If you want 1000 converted to just 1,000, then you can use the following:
This splits the string at the decimal point and returns whatever is after the decimal point as was typed in BUT formats the integer part of the number with commas.