Best way to check if a floating-point number can safely be converted to an integer

Godot Version

v4.6.2.stable.official [71f334935]

Question

What is the best or better way of checking that a numeric value (already) stored in a floating-point data type can safely be converted to an integer? I have valid reasons for storing these values in a floating-point data type as any number of other operations could have been performed on them beforehand that could result in floating points which I want to retain.

At times I may want to pass these values onto sub-functions but I don’t just want to cast the value to an integer. If it is an integer it’ll get sent one way and if a floating point another.

With strings before conversion to a number I could just use .is_valid_int() or .is_valid_float(), but I can’t see similar for values already in numeric data types. Same is some other languages.

For the moment I could use one of the two below functions but I’m looking for the best approach. I prefer option one, or is there an inbuilt method or a better way I’m missing.

EDIT: Updated title and question to better explain my reasoning, hopefully.

Option 1

func is_int(value: float) -> bool:
	if not fmod(value, 1):
		return true
	return false

Option 2

func is_int(value: float) -> bool:
	if floor(value) == value:
		return true
	return false

Floating point values can never be int values.

If you want to check if a float number is near to closest integer, I’d go with something like: abs(round(value) - value) < some_very_small_threshold

1 Like