Reputation: 918
My code:
public decimal SetHourRate(string hourrate)
{
var value = decimal.Parse(hourrate, NumberStyles.Currency, CultureInfo.CurrentCulture.NumberFormat);
return value;
}
In parameter:
string hourrate = "800.00"
My problem:
Right now my output is like var value = 80000
? I want it to be like the string I put in. I'm from Sweden and we have a dot instead of comma to separate the decimals in currency. It must work even if the string look like this string hourrate = "1050.67"
.
It's ok if the output will be like var value = "800,00"
or var value ="1050,67"
(comma instead of dot.)
Upvotes: 1
Views: 2192
Reputation: 268
You have to use CultureInfo to specify what formatting to use when parsing.
CultureInfo culture = new CultureInfo("sv-SE");
culture.NumberFormat.NumberDecimalSeparator = ".";
decimal value;
if (decimal.TryParse(hourrate, NumberStyles.Currency, culture, out value))
{
// Do what you want with value if successfully parsed
}
else
{
// Failed to parse
}
Make sure you include System.Globalization
at the top of your code.
Upvotes: 1
Reputation: 38598
It is returning the 80000
because the .
in the swedish is the GroupSeparator. The ,
is the decimal separator.
You are passing a string like 800.00
so, .
will be used as group separator. That is the reason you are getting this value.
You could force the decimal separator to be .
chaging the a formater (CultureInfo), for sample:
public decimal SetHourRate(string hourrate)
{
var swedishCulture = new CultureInfo("sv-SE");
swedishCulture.NumberFormat.NumberDecimalSeparator = ".";
var value = decimal.Parse(hourrate, NumberStyles.Currency, swedishCulture);
return value;
}
Upvotes: 1