I’m making a calculator application for windows phone 7 and I’m struggling with digit grouping. Here’s the code:
myNumber = myNumber.Replace(“,”, string.Empty);
int dot = myNumber.IndexOf("0.");
strNumberWithoutDecimals = myNumber.Substring(0, (dot == -1 ? myNumber.Length : dot));
strNumberDecimals = (dot == -1 ? "" : myNumber.Substring(dot));
try
{
strNumberWithoutDecimals = Convert.ToDouble(strNumberWithoutDecimals).ToString("#,##0.000000000");
}
catch (Exception)
{
//Ignore ... for now.
}
total = strNumberWithoutDecimals + strNumberDecimals; return total;
The problem is when the user enters say 0.323 and the digit grouping is on, the number can’t be negative. It won’t work. 0.323 cannot become -0.323 and I don’t know why. Any help would be highly appreciated. Thanks in advance.
You should be familiar with C# string formatting support, both on input and output.
http://blog.stevex.net/string-formatting-in-csharp/
Use
Double.TryParse()with one of the overloads that includes style information.e.g.
TryParse(string s, NumberStyles style, IFormatProvider provider, out double result)(There should be similar methods for Integer, Decimal, Float, etc depending on the precision you require).
This approach will also make your app more I18N friendly, as different cultures employ different conventions for digit grouping (e.g. many European cultures do 1.234.567,89 to represent 1,234,567.89)
TryParse(string s, out double result)should also work but with less control over the format of the input string.These are functionally equivalent:
Note that
NumberStyles.Floatis a composite of other NumberStyles (e.g.NumberStyles.AllowLeadingSign,NumberStyles.AllowDecimalPoint, etc).No need to manually strip out commas, etc!
See MSDN for more info.