Search code examples
c#stringunity-game-enginestring-formattingformatexception

FormatException when custom button is pressed the second time


In unity 2d c# I created a custom button, and when pressed the first time it works perfectly, but when the button is pressed a second time I received an error "FormatException: Input string was not in a correct format.", (I think the error is in the StockTransferBuy method) it does not need to be in float, but I need it to be stored in two decimal places. Thanks in advance. Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class Stock : MonoBehaviour
{
    public int minRange;
    public int maxRange;
    public float oldPrice;
    public float currentPrice;
    private bool isRising;
    public Image greenArrow;
    public Image redArrow;
    public int StockOwned;
    
    public TMP_Text StockPrice;
    public TMP_Text Money;


    // Start is called before the first frame update
    void Start()
    {
        int startAt = Random.Range(minRange, maxRange);
        oldPrice = Random.Range(startAt + 0.0f, maxRange + 0.0f);

        isRising = Random.Range(1, 3) == 1;
        
        if (isRising)
        {
            currentPrice = Random.Range(oldPrice + 0.0f, ((maxRange - minRange) + oldPrice) + 0.0f);
        }
        else
        {
            currentPrice = Random.Range(oldPrice + 0.0f, ((minRange - maxRange) + oldPrice) + 0.0f);
        }

        StockPrice.text = string.Format("{0:N2}", oldPrice) + " -> " + string.Format("{0:N2}", currentPrice);
    }

    // Update is called once per frame
    void Update()
    {
        greenArrow.gameObject.SetActive(isRising);
        redArrow.gameObject.SetActive(!isRising);
    }

    public void StockTransferBuy()
    {
        Money.text = string.Format("{0:N2}", (float.Parse(Money.text, 0.0f) - currentPrice));
        StockOwned++;
    }


}

I'm not sure why the error happened, I assume it was because I formatted the Money.text to be string.Format("{0:N2}", value) and I tried using .ToString(#.##) but that did not work I kept receiving errors.


Solution

  • Change float.Parse(Money.text, 0.0f) to float.Parse(Money.text) and it will likely work.

    You cannot use 0.0f as a NumberStyle. See the MS docs for valid values: https://learn.microsoft.com/en-us/dotnet/api/system.globalization.numberstyles?view=net-7.0#system-globalization-numberstyles-float