My web application deals with strings that need to be converted to numbers a lot - users often put commas, units (like cm, m, g, kg) and currency symbols in these fields so
public static double ToDecimal(this string value)
{
... your parsing magic
}
The biggest problem is that you must know the Culture in which the user enters the number. Otherwise you will run into big problems.
A little example is the to read your number as english or german one.
In english the NumberFormatInfo.CurrencyDecimalSeparator is a dot (.) and the NumberFormatInfo.CurrencyGroupSeparator is a comma (,). In german it is exactly the other way around. So you can start wild guessing if the user means one thousand two hundred fifty or one and a fourth dollar.
Maybe you can run over all available Cultures and check if your user input contains a NumberFormatInfo.CurrencySymbol and then try the given culture. But maybe there are cultures which use the same Symbol but different Separators.
So to get this really to work you have just two really choices: * Tell your users in which culture format they have to enter their values. * Give the user the possibility to tell you which culture they decided to do.
A list of all available cultures can be get by CultureInfo.GetCultures()
An extension method is of the following form:
public static class StringExtensions
{
public static decimal ToDecimal(this string input)
{
//your conversion code here
}
}
Here is a guide for writing extension methods.
The most appropriate way to solve this problem seems to me to be to use the overload of Decimal.TryParse
that accepts a NumberStyles
and a culture. Pass it NumberStyles.Currency
and an appropriate culture.
Now, there's nothing stopping you providing an extension method on string
that calls this - but you do need to consider what you would like the value of d
to be after
decimal d = "ponies".ToDecimal();
Just answering the how do I create extension method for string class:
public static class MyStringExtensions {
public static ToDecimal(this string input) {
// ...
}
}
(and you need to have an using statement for the namespace it is located in order to use it)
Please read this article about currency implementations:
https://docs.microsoft.com/en-us/globalization/locale/currency-formatting
Example:
Double myNumber = Double.Parse("$1,250.85", NumberStyles.Any);
PS. You trying parse floating point value to decimal type.