Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am writing a game in Unity where I need to convert a TextMeshProUGUI text into a float, but for some reason this code:

C#
float num = float.Parse(inputText.text);

Gives me this error:

Terminal
FormatException: Input string was not in a correct format.
System.Number.ThrowOverflowOrFormatException (System.Boolean overflow, System.String overflowResourceKey) (at <d4cde64232cf45659d86aafa597faa77>:0)
System.Number.ParseSingle (System.ReadOnlySpan`1[T] value,
System.Globalization.NumberStyles styles, System.Globalization.NumberFormatInfo info) (at <d4cde64232cf45659d86aafa597faa77>:0)
System.Single.Parse (System.String s) (at <d4cde64232cf45659d86aafa597faa77>:0)

Why is this happening? How is a string with a simple number (i used 1 as an example) not the right format? Thank you in advance.

What I have tried:

I have tried doing:
C#
inputText.text.ToString()

I also added null and empty string checking
I even tried:
C#
string numText = inputText.text.ToString();
float numFloat = float.Parse(numText, CultureInfo.InvariantCulture);

None of it is working.
Posted
Updated 23-Oct-22 18:53pm
v2

1 solution

We can't tell: it need your code running in context with your inputs to find out.
Certainly for me, an input of "1" gives no exception:
C#
using System;
					
public class Program
{
	public static void Main()
	{
		string input = "1";
		Console.WriteLine(float.Parse(input));
	}
}
Which means that your input has to be different to that, or your environment is wildly different!

So do two things.
1) Stop assuming user input will always be correct, and use the TryParse methods instead:
C#
using System;
					
public class Program
{
	public static void Main()
	{
		string input = "1";
		float f;
		if (!float.TryParse(input, out f))
		{
			Console.WriteLine($"\"{input}\" is not a valid floating point value");
			return;
		}
		Console.WriteLine(f);
	}
}
2) Use the debugger to look at exactly what is going on. Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900