Number Parsing in GDScript

Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in GDScript.

extends Node

func _ready():
    # With float(), we can parse floating-point numbers
    var f = float("1.234")
    print(f)

    # For integer parsing, we can use int()
    var i = int("123")
    print(i)

    # GDScript doesn't have built-in hex parsing, but we can use this method
    var d = ("0x1c8").hex_to_int()
    print(d)

    # For unsigned integers, we can use the same int() function
    var u = int("789")
    print(u)

    # GDScript doesn't have a separate function for base-10 int parsing
    # We can use the same int() function
    var k = int("135")
    print(k)

    # Parsing functions will return 0 on bad input
    var e = int("wat")
    print(e)

To run this script, attach it to a Node in your Godot scene and run the scene. The output will be printed to the Godot output panel.

1.234
123
456
789
135
0

In GDScript, number parsing is generally simpler than in some other languages:

  • float() is used to parse floating-point numbers.
  • int() is used to parse integers. It doesn’t require specifying a base or bit size.
  • For hexadecimal numbers, we use the hex_to_int() method on strings.
  • There’s no separate function for parsing unsigned integers; int() is used for all integer types.
  • GDScript doesn’t have a direct equivalent to Atoi, but int() serves the same purpose for base-10 integer parsing.
  • Unlike some languages, parsing functions in GDScript don’t return errors. Instead, they return 0 for invalid input.

Next, we’ll look at another common parsing task: URLs.