C # Converting a string to double / decimal and back to a string, saving trailing zeros, adding coms for thousands

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 the decimal numbers (including trailing zeros) 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); 
+5
source share
4 answers

double.Parse(input) is not, because double does not track the number of decimal places.

decimal.Parse(input).ToString() will show that decimal tracking this. Unfortunately, decimal.Parse(input).ToString() uses this precision and does not use the thousands separator, and decimal.Parse(input).ToString("N") ignores the precision, but uses the thousands separator.

Manually extracting precision from a decimal number works, and this allows you to build the correct format string:

 static string InsertThousandsSeparator(string input) { var dec = decimal.Parse(input); var bits = decimal.GetBits(dec); var prec = bits[3] >> 16 & 255; return dec.ToString("N" + prec); } 

This is based on the decimal layout, as described on MSDN :

Bits 16 through 23 should contain an index between 0 and 28, which indicates the power of 10 to divide an integer.

See how it works on the .NET Fiddle. (courtesy of @Alisson)

+7
source

You can use the regular expression for this:

 var input = "1000.50000"; var regex = new Regex("^(?<int>-?[\\d,]+)\\.(?<fract>\\d+)$"); var match = regex.Match(input); var integralPart = match.Groups["int"].Value.Replace(",", ""); var fractionalPart = match.Groups["fract"].Value; var result = $"{decimal.Parse(integralPart):n0}.{fractionalPart}"; 
0
source
  public string DoFormat(string num) { int pt = num.IndexOf("."); if (pt > 0) { return string.Format("{0:#,##0}", num.Substring(0, pt)) + num.Substring(pt, num.Length - pt); } else { return string.Format("{0:#,##0}", num); } } 

This splits the string at the decimal point and returns everything that after the decimal point, as was introduced in BUT, formats the integer part of the number with commas.

0
source

If you do not mind 1000 convertibles to 1000.00, then the following is the best, as it also takes into account the user language.

 string output = String.Format("{0:n}", input); 

If you want 1000 to convert to 1000, you can use the following:

 string output2 = String.Format("{0:#,##0.##}", input); 
-1
source

Source: https://habr.com/ru/post/1270235/


All Articles