How do I add fractions in a textlabel

I have a text label that says “1/10.” When the player clicks a circle on the screen, I’d like the number to go to “2/10” ← (Add 1/10 to the text label when the player clicks the circle)

How do I add fractions in a textlabel? I tried using “tonumber” on the textlabel and adding 1/10 but it returns a nil value. I also tried using “intvalues” but it only got me more confused.

Thank you for your help.

tonumber(“1/10”) will return nil as the “/” character is not numeric. I’d approach this by splitting the string currently in the text label using “/” as the separator. This will return a table where we can reference the first index as the numerator and the second the denominator:

local fraction = string.split(textLabel.Text, "/")
textLabel.Text = string.format("%d/%d", fraction[1]+1, fraction[2])

If you wanted to clamp the numerator to not exceed the denominator you could use math.clamp:

textLabel.Text = string.format("%d/%d", math.clamp(fraction[1]+1, 0, fraction[2]), fraction[2])

For more info: math.clamp, string.split

3 Likes

Thank you for your help, it works!

To any future readers, make sure you use [ ] and not { } by accident.

1 Like