Reputation: 31
I can not convert from string into decimal this is the value of lblTotal="110,00€" I want to convert it to decimal how can I convert it?
decimal number;
if( Decimal.TryParse(((Label)e.Item.FindControl("lblTotal")).Text.ToString(), out number))
{
}
Upvotes: 0
Views: 556
Reputation: 19179
You can use CultureInfo.CreateSpecificCulture with culture code of Countries using Euro as currency.
Table of Language Culture Names, Codes, and ISO Values Method.
for example Greece, Ireland, Italy uses this currency.
Simply
decimal resault = decimal.Parse(((Label)e.Item.FindControl("lblTotal")).Text.ToString()
,NumberStyles.Currency
,CultureInfo.CreateSpecificCulture("it-IT"));
This will convert your string "110,00€"
to decimal correctly Since Italy uses euro(€
) as currency.
Or you can use another Culture by searching in the provided link.
Upvotes: 0
Reputation: 98858
If you can't parse your string, there can be a few possibilities..
First of all, Decimal.TryParse
uses NumberStyles.Number
style and this does not includes Currency
style. Both are composite styles. That's why you need to use another overload that specify currency symbol and decimal separator.
Second, your Decimal.TryParse
uses CurrentCulture
settings by default. That means, your CurrencySymbol
is not €
and/or your NumberDecimalSeparator
is not ,
.
As a best solution, you can Clone
your CurrentCulture
and set these properties with Currency
style like;
var clone = (CultureInfo) CultureInfo.CurrentCulture.Clone();
clone.NumberFormat.CurrencySymbol = "€";
clone.NumberFormat.NumberDecimalSeparator = ",";
decimal number;
if(decimal.TryParse(((Label)e.Item.FindControl("lblTotal")).Text,
NumberStyles.Currency, clone, out number))
{
// You can use number here
}
Upvotes: 3
Reputation: 216353
You should inform the Decimal.TryParse that you have a currency symbol and what is your culture
string test = "110,00€";
if( Decimal.TryParse(test, NumberStyles.Currency, CultureInfo.CurrentCulture, out number))
{
Console.WriteLine(number);
}
I would also recommend to use a more defensive approach to your retrieving of the label to parse.
Label lbl = e.Item.FindControl("lblTotal") as Label;
if(lbl != Null)
{
.....
}
Upvotes: 2