How to Always Show 2 Places After a Decimal Point - Such as when using dollars and cents

Hey All,

I’m working on a shop script to buy/sale items and using math to show a total dollar and cent value. I can’t figure out how to make the final value of a sale to always show the two digits following a decimal points.

For example:
If an item costs .25 and the player buys 5 of them, the total shown is $1.25.
If the player buys 6 of the the total shown is $1.5
I’m trying to make the total read $1.50.

Basic example script:

local totalAmount = player.PlayerGui.ScreenGui.ShopFrame.TotalLabel  --What will hold the final value
local item1 = .25  -- cost of each item
local quantity = player.PlayerGui.ScreenGui.ShopFrame.Quantity.Value -- quantity selected

totalAmount.Value = (item1 * quantity)  -- assigns the final cost, but removes zeros at the end

Any thoughts on how to always show two places after the decimal point, even if they are zeros?

1 Like

String formatting is what is needed here. When you want to display the total, just use a format like this

string.format("%.2f", TOTALAMOUNTHERE)

This would put at least 2 decimal places, although this will also do it to full whole numbers as well

@heII_ish Yeah my bad, just woke up and didn’t read the documentation properly

5 Likes

You can use the %.2f format and then format your string.

string.format("%.2f", 1) --> 1.00
string.format("%.2f", 1.5) --> 1.50
string.format("%.2f", 1.558) --> 1.56

@EmbatTheHybrid The format string actually comes first

2 Likes

how would i do it so if its greater than 2 characters it formats but if its just 1 character it stays