- Home /
TMPro Input Field : can't parse float
HI, I am having an annoying issues, hope anyone has a solution. I cannot seem to parse a float from an TMPro InputField. Has soon as I add a period in the input field, parsing fail. Works find for any integer number.
float time = 0;
if (float.TryParse(timeIF.text, out float _time))
{
Debug.Log("parse OK");
time = _time;
}
else
{
Debug.Log("parse KO");
time = 0;
}
Input is set to Decimal Numbers. Does anyone have a clue what's going on ? Best,
Answer by myzzie · Aug 18, 2020 at 08:43 PM
You either replace periods with commas or commas with periods and change the culture Info in your parser.
using System.Globalization;
string decimalString = "1,6";
string periodString = "1.6";
float value = float.Parse(decimalString, NumberStyles.Any, CultureInfo.CurrentCulture);
float value2 = float.Parse(periodString, NumberStyles.Any, new CultureInfo("en-US"));
Both return a float value of 1.1
Answer by Spip5 · Aug 18, 2020 at 07:48 PM
Alright, got it. That's a really counter-intuitive behaviour : if the TMPro input field is set as decimal, it accepts periods to separate integer and decimals, but the float parse actually needs commas...
float time = 0;
Debug.Log(timeIF.text);
Debug.Log(timeIF.text.Length);
if (float.TryParse(timeIF.text.Replace(".",","), out float _time))
{
Debug.Log("parse OK");
time = _time;
}
else
{
Debug.Log("parse KO");
time = 0;
}
Your answer

Follow this Question
Related Questions
GUI Text/Buttons acting strangely despite similarities to normal-acting UI elements 1 Answer
TextMeshPro input field returning different string to standard input string 1 Answer
Text Material overlay not supporting Masks 0 Answers
I am getting this error !PLEASE HELP 0 Answers
TextMesh Pro Page content 2 Answers