Link to home
Start Free TrialLog in
Avatar of IRQ
IRQ

asked on

Currency string convertion

If I convert a decimal representing a money sum to a string, I preferably do it using a sum.ToString("C"). The result is something like "$123.45" or "123,45 kr", depending on your regional settings in Windows (I guess!?).

How do I convert back from the string to a decimal/float/similar? Is there a function that trims the string dependant of the regional settings?
Avatar of glsac
glsac
Flag of United States of America image

Avatar of Joeisanerd
Joeisanerd

If that doesn't work you may need to look at the specifics in the NumberFormatInfo.CurrentInfo object like below

string sep = System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator;

and the currency symbol

string symbal = System.Globalization.NumberFormatInfo.CurrentInfo.CurrencySymbol;

there are some more options in there that you can then use to convert the currency string back to the a float.
                  
Here is a very basic example

// replace the seperator either . or , or something else with a . and also replce the currency symbol with nothing
// affectively deleting it.
string sep = System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator;
string sym = System.Globalization.NumberFormatInfo.CurrentInfo.CurrencySymbol;
string total = txtTotal.Text;

total = total.Replace(sep,".");
total = total.Replace(sym,"");

MessageBox.Show(total);
Avatar of IRQ

ASKER

Thanks guys, I made it myself by:
myDecimal = decimal.Parse(myString, NumberStyles.Currency, NumberFormatInfo.CurrentInfo);

Was that the same solution as yours, J?
same idea, but yours is cleaner!
ASKER CERTIFIED SOLUTION
Avatar of ee_ai_construct
ee_ai_construct
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial