Safe conversion from FString to float?

Is there a safe way to convert from an FString of unknown content to a float (or int)? The wiki states on this page that I should use FCString::Atof(), but ideally I would like to check that the string is reasonable to convert prior to calling this and handle poor input as needed.

For example, if an input string is β€œfoo” it is not safe to call FCString::Atof().

1 Like

what about checking if there are only numbers in it?

Hehe, fair enough. I was more looking for a pre-written function if there was one so that I could avoid writing unnecessary code. The function exists so I’ve answered and marked it as correct.

Clearly, I did not read the docs carefully. The function I was looking for was FString::IsNumeric().

I recommend FDefaultValueHelper::ParseFloat if you need the string to have decimals. IsNumeric() would return false with β€œ12.12” because of the β€˜.’ while ParseFloat recognises it’s a float.

1 Like

The isNumeric function is like this in the engine:

	static bool IsNumeric(const CharType* Str)
	{
		if (*Str == '-' || *Str == '+')
		{
			Str++;
		}

		bool bHasDot = false;
		while (*Str != '\0')
		{
			if (*Str == '.')
			{
				if (bHasDot)
				{
					return false;
				}
				bHasDot = true;
			}
			else if (!FChar::IsDigit(*Str))
			{
				return false;
			}
			
			++Str;
		}

		return true;
	}

β€œ12.12” should still be considered as numeric as long as there is only one decimal point.