I am making a game and the highest number in the game possible is: 9999999 and in the UI text display box is a little hard to differentiate how much money the player actually has without commas. Now is there any builtin function in gdscript that will add the commas into the text string? Apparently this exists in Python and JavaScript.
If not, do you know of any YouTube vids that show this being done in Godot.
I don’t know of any tutorial for that, and I can’t find any built-in function neither. So, here’s a simple function doing what you want:
func format_number_with_dots(number: int) -> String:
var num_str: String = str(abs(number))
var result: String = ""
var count: int = 0
for i in range(num_str.length() - 1, -1, -1):
result = num_str[i] + result
count += 1
if count % 3 == 0 and i != 0:
result = "." + result
if number < 0:
result = "-" + result
return result
Used like this:
var number: int = 89979900
print(format_number_with_dots(number))
# Output: 89.979.900
It simply converts the number to a string, loop through the digits, and adds a dot every group of three digits. You can replace the dot by a comma or any character, on that line: result = "." + result
Also, the function takes negative numbers into account, which is convenient and should be kept for a helper function like this, but for a score, maybe you don’t want that. Up to you.
That is going to fail on negative numbers because you add the - back on at the end without first removing it.
Suggested change:
func format_number_with_dots(number: int) -> String:
var num_str: String = str(number).lstrip("-") # this line changed
var result: String = ""
var count: int = 0
for i in range(num_str.length() - 1, -1, -1):
result = num_str[i] + result
count += 1
if count % 3 == 0 and i != 0:
result = "." + result
if number < 0:
result = "-" + result
return result
Thankyou so much for your reply! I really didn’t expect anyone to post actual code instead just point me to a tutorial, but, this is going to save me SOOO much time and effort.
Whoops, that’s correct.
I believe that taking the absolute number is more efficient than removing the sign, but you’re right, I’ll edit my answer as it’s been tagged as solution.
Thank you!