简体   繁体   中英

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 .

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

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