How to add commas to an integer or float in GDScript?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ZeBirosca
:warning: Old Version Published before Godot 3 was released.

For example

I have a variable named money:

var money = 1234

and I want to print this variable like this:


How to do this?

:bust_in_silhouette: Reply From: flesk

In lieu of a decimal formatter or a regex replace function in Godot, you can implement your own helper function in a singleton by casting the number to a string and using the modulo operator to insert a comma for every three characters.

Something like this:

func comma_sep(number):
    var string = str(number)
    var mod = string.length() % 3
    var res = ""

    for i in range(0, string.length()):
	    if i != 0 && i % 3 == mod:
		    res += ","
	    res += string[i]
    return res

It will need some tweaking depending on the format of the numbers you want to support though.

Thank you.

I thought that Godot had a fuction to do this for me, like the format() thing in python.

ZeBirosca | 2017-10-03 23:20

Yeah, in Python it would be as simple as "{:,}".format(number), if memory serves. Not so in Godot, unfortunately.

flesk | 2017-10-04 04:44

:bust_in_silhouette: Reply From: burstina

to add only comma for EUR values, something like that works fine:

func Euro(price):
	return str("%-3.2f" % price).replace(".",",")
:bust_in_silhouette: Reply From: Poobslag

Here’s a more concise form of the comma_sep function which I use in my game:

static func comma_sep(n: int) -> String:
	var result := ""
	var i: int = abs(n)
	while i > 999:
		result = ",%03d%s" % [i % 1000, result]
		i /= 1000
	return "%s%s%s" % ["-" if n < 0 else "", i, result]
:bust_in_silhouette: Reply From: MrFlamey

This simple while loop technique works for formatting scores:

func format_score(score : String) -> String:
	var i : int = score.length() - 3
	while i > 0:
		score = score.insert(i, ",")
		i = i - 3
	return score