0

Checking for number 3 in Text

error:

The input string was not in the correct format

public Text Timer;
   
    private void FixedUpdate()
    {
        if (Convert.ToDouble(Timer.text) == 3)
        {
            Debug.Log("w");
        }
    }
  • Was the text box empty? – jdweng Jul 01 '20 at 23:13
  • you are better off with Double.TryParse it will tell you if the field is not correct https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=netcore-3.1 – pm100 Jul 01 '20 at 23:16
  • Print your `Timer.text` as `Debug.Log("'" + Timer.text + "'");`. Note single quote in double quotes. – Malphegal Jul 02 '20 at 01:29

1 Answers1

0

we don't know which string content your Time.text has but you should rather use either double.TryParse or since everything in the Unity API uses float anyway maybe rather float.TryParse. Alternatively you can also cast it to (float) since you are wanting to compare it basically to an int value anyway the precision doesn't really matter.

Because a second point is: You should never directly compare floating point type numbers via == (See How should I do floating point comparison?). It is possible that a float (or double) value logically should have the value 3 like e.g. (3f + 3f + 3f) / 3f but due to the floating point imprecision results in a value like 2.9999999999 or 3.000000001 in which case a comparing to 3 might fail unexpectedly.

Rather use the Unity built-in Mathf.Approximately which basically equals using

if(Math.Abs(a-b) <= epsilon)

where Mathf.Epsilon

The smallest value that a float can have different from zero.

So I would recommend to rather do something like

if (double.TryParse(Timer.text, out var time) && Mathf.Approximately((float)time, 3))
{
    Debug.Log("w");
}

Note however that if this is a timer that is continuously increased you might never exactly hit the value 3 so you might want to either use a certain threshold range around it like

if (double.TryParse(Timer.text, out var time) && time - 3 >= someThreshold)
{
    Debug.Log("w");
}

or simply use e.g.

if (double.TryParse(Timer.text, out var time) && time >= 3)
{
    Debug.Log("w");
}

if you only want any value bigger or equal to 3.

derHugo
  • 83,094
  • 9
  • 75
  • 115