简体   繁体   中英

How can i Convert string to decimal

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))
{

}

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
}

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)
{
   .....
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM