[英]Getting a format exception parsing a string to a double
So there are still some logic errors in this that I am working on. 因此,我正在研究中仍然存在一些逻辑错误。 I'm not worried about those, and I want to figure them out myself.
我不担心这些,我想自己弄清楚它们。
I'm working on a slot machine app for some independent study and when I try to parse the value of the label that shows the players cash into a variable I am getting a format exception. 我正在使用老虎机应用程序进行一些独立研究,当我尝试将标签上显示玩家现金的标签的值解析为变量时,出现格式异常。 How do fix this and more importantly why am I getting this exception?
如何解决此问题,更重要的是为什么我会收到此异常?
I have also tried using TryParse
and Convert.ToDouble
. 我也尝试过使用
TryParse
和Convert.ToDouble
。
protected void PullBTN_Click(object sender, EventArgs e)
{
// Get players cash//////////////////////////////
double playersCash = Convert.ToDouble(playerMoneyLBL.Text);
// Other way I tried that didn't work ////////////
//double playersCash = 0;
//double.TryParse(playerMoneyLBL.Text.Trim(), out playersCash);
// Get players bet /////////////////////////////
double playerBet = 0;
if (!double.TryParse(betTB.Text, out playerBet))
return;
// Spin the slots//////////////////////////////
Image1.ImageUrl = spinReel();
Image2.ImageUrl = spinReel();
Image3.ImageUrl = spinReel();
// Find multiplier //////////////////////////////
double multiplier = findMultiplier();
// Find winnings ///////////////////////////////
double winnnings = multiplier * playerBet;
playerMoneyLBL.Text = (playersCash + winnnings).ToString();
// Add winnings to players money //////////////
playerMoneyLBL.Text = (playersCash + winnnings).ToString();
}
Your problem is here. 您的问题在这里。
playerMoneyLBL.Text = "$100";
As you have $
in-front of 100, you cannot convert that to float. 由于您的
$
前面有100,因此无法将其转换为float。 Make it something like this. 使它像这样。
double playersCash = Convert.ToDouble(playerMoneyLBL.Text.substring(1));
double.Parse uses your CurrentCulture settings on the current environment by default. double。默认情况下,Parse在当前环境上使用CurrentCulture设置。
double d = double.Parse("Your Text Here", CultureInfo.InvariantCulture);
Or if you want it more secure way, try: 或者,如果您想要更安全的方法,请尝试:
value = "Your String";
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol| NumberStyles.AllowThousands;
culture = CultureInfo.InvariantCulture
if (Double.TryParse(value, style, culture, out number))
{
// Write your code for true condition
}
else
{
// Write your code for false condition
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.