[英]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? 我无法从字符串转换为十进制,这是lblTotal =“ 110,00€”的值,我想将其转换为十进制如何转换?
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. 首先,
Decimal.TryParse
使用NumberStyles.Number
样式,这不包括Currency
样式。 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. 其次,默认情况下,您的
Decimal.TryParse
使用CurrentCulture
设置。 That means, your CurrencySymbol
is not €
and/or your NumberDecimalSeparator
is not ,
. 这意味着,你的
CurrencySymbol
不€
和/或你的NumberDecimalSeparator
不是,
。
As a best solution, you can Clone
your CurrentCulture
and set these properties with Currency
style like; 作为最佳解决方案,您可以
Clone
CurrentCulture
并使用Currency
样式设置这些属性,例如;
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 您应该通知Decimal.TryParse您有货币符号以及您的文化是什么
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. 您可以将CultureInfo.CreateSpecificCulture与使用欧元作为货币的国家/地区的文化代码一起使用。
Table of Language Culture Names, Codes, and ISO Values Method . 语言文化名称,代码和ISO值方法表 。
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. 这将正确地将字符串
"110,00€"
转换为十进制,因为意大利使用的是欧元( €
)作为货币。
Or you can use another Culture by searching in the provided link. 或者,您可以通过搜索提供的链接来使用其他文化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.