[2.0] Double to Currency and back to Double
After a double has been formatted to currency, is there no way to convert the currency string back to a double for calculations?
I though specifying the CultureInfo may help in the conversion but it doesn't.
Code:
CultureInfo ci = Thread.CurrentThread.CurrentCulture;
double d = -56254.3856;
string strInput = String.Format(ci, "{0:c}", d);
Console.WriteLine(strInput); // ($56,254.39)
d = Convert.ToDouble(strInput, ci); // fails
Console.WriteLine(d);
What's the simplest way to do this?
Re: [2.0] Double to Currency and back to Double
Nevermind, I hate it when I do that...
Code:
CultureInfo ci = Thread.CurrentThread.CurrentCulture;
double d = -56254.3856;
string strInput = String.Format(ci, "{0:c}", d);
Console.WriteLine(strInput); // ($56,254.39)
Double.TryParse(strInput, NumberStyles.Currency, ci, out d);
Console.WriteLine(d); // -56254.39
Re: [2.0] Double to Currency and back to Double
Just note that it is preferable to use the Decimal type for currency rather than Double if possible because floating-point types like Double and Single can be susceptible to round-off errors.
Also, the current culture will be used by default if you don't specify so there's no need to specify unless you want to use other than the current culture:
Code:
decimal d1 = -56254.3856m;
MessageBox.Show(d1.ToString());
string s = d1.ToString("c");
MessageBox.Show(s);
decimal d2;
decimal.TryParse(s, System.Globalization.NumberStyles.Currency, null, out d2);
MessageBox.Show(d2.ToString());
Re: [2.0] Double to Currency and back to Double
Quote:
Originally Posted by jmcilhinney
Just note that it is preferable to use the Decimal type for currency rather than Double if possible because floating-point types like Double and Single can be susceptible to round-off errors.
Also, the current culture will be used by default if you don't specify so there's no need to specify unless you want to use other than the current culture:
Thanks for the tips.
I was enumerating cultures to show the differences in currency formats. That makes sense that the current culture would be used by default.
Why is it that decimal isn't used for extended precision in the Math class? Most of the functions still return double.
Technically, any number experiences round-off error at some point, even decimal, albeit less error than others.
Re: [2.0] Double to Currency and back to Double
Because of the way there are stored, floating-point types (Double, Single) cannot represent all values. Some values have to be rounded-off to the nearest value that can be represented. Fixed-point types (Decimal) are not susceptible to the errors that can creep in due to this fact, but they occupy more space and are slower to work with.