In GDScript, the round(X) function does not return an integer by default. Instead, it returns a float, even if the result of the rounding is a whole number.
Key Points:
Return Type: The round(X) function in GDScript always returns a float. This is consistent with many other programming languages like C++, JavaScript, and GDScript's own design principles, where mathematical operations typically return float values unless explicitly cast otherwise.
Example Behavior:
gdscript
var a = round(3.2) # Returns 3.0 (float)
var b = round(3.7) # Returns 4.0 (float)
var c = round(5.0) # Returns 5.0 (float)
Type Verification:
You can confirm the return type using the typeof() function:
gdscript
print(typeof(round(3.2))) # Output: 3 (which corresponds to TYPE_REAL, i.e., float)
Why Not an Integer?
GDScript treats int and float as separate types.
Since round(X) is a mathematical function, it's more natural for it to return a float, especially since it may be used in contexts where precision is important (e.g., physics calculations, graphics).
Returning a float also aligns with how similar functions behave in other languages and avoids ambiguity in type handling.
Casting to Integer (When Needed):
If you need an integer result, you must explicitly cast the output of round(X) to an integer:
gdscript
var rounded_int = int(round(3.7)) # Converts 4.0 to 4 (int)
Practical Implication:
When using the result of round(X) in contexts that require integers (such as array indexing or bitwise operations), you must cast the result to an integer. Failing to do so will result in a type mismatch error.
gdscript
var arr = [10, 20, 30]
var index = round(1.5) # Returns 2.0 (float)
# arr[index] = 42 # This will cause an error
arr[int(index)] = 42 # Correct usage
Conclusion:
No, the round(X) function in GDScript does not return an integer by default. It returns a float, and you must explicitly cast it to an integer if that's the type you need.