Humanize Numbers

Godot Version

4.3

Question

I am working on a game that works with large numbers being displayed to the player, I thought there was a way to humanize/format numbers (so ‘1000’ becomes ‘1,000’, etc) as a built-in function of Strings, but I looked through all the String functions and couldn’t find it.

Does a function like that exist or would I have to make one custom?

Thanks.

The closest thing I’m aware of is this from the documentation, which is the built in GdScript means of string formatting: GDScript format strings — Godot Engine (stable) documentation in English

1 Like

Thanks! I hadn’t seen these before except for the String.format() function, but they didn’t end up working. So I ended up making my own custom function, which for anyone in the future reading this is;

func humanize_number(number : String) -> String:
	var to_return : String
	var decimals : String
	if "." in number:
		decimals = "." + number.split(".", false, 0)[1]
	if len(number.replace(decimals, "")) < 4:
		return number
	else:
		var i : int = 0
		for item in number.replace(decimals, "").reverse():
			if i == 3:
				item += ","
				i = 0
			to_return = item + to_return
			i += 1
		return to_return + decimals

Hopefully in the future we can have a built-in function which does a similar thing.

2 Likes

Any time! I’m new to the engine but someone showed me that maybe 2 days back to make a timer display look correct.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.