Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How can I add a constant character to a string with a variable?

Asked by 7 years ago

In case my title was awfully phrased, I want to have a TextLabel that gets its value from Player.leaderstats.Cash and it works well except for that I want it to always have a "$" in front of the Cash.Value

local player = game.Players.LocalPlayer
player.PlayerGui:WaitForChild("Balance")
local cashText = player.PlayerGui.Balance.CashBal

player.leaderstats.Cash.Changed:connect(function()
    cashText.Text = game.Players.LocalPlayer.leaderstats.Cash.Value
end)

here's the hierarchy just in case https://gyazo.com/09cffa0a3c50fc41682931e580dc51b8

1 answer

Log in to vote
2
Answered by
XAXA 1569 Moderation Voter
7 years ago
Edited 7 years ago

If you want to go simple, you can just concatenate to the beginning/end.

print("$" .. 1234) -- prints "$1234"

However, the preferred way is to use string.format

print( string.format("$%d", 1234)) -- also prints "$1234". 
-- "%d" in the string pattern indicates that we want to replace it with a number.

The advantage of the second method is that it is more extensible. If you want to print out extra decimal places for fun, you can change it up, like so:

print( string.format("$%0.2f", 1234)) -- prints "$1234.00"
-- "%0.2f" indicates that we want to print a number with decimal digits, up to the second digit after the decimal point.

More about Format Strings in Roblox Wiki.

1
thanks a lot! creeperhunter76 554 — 7y
1
Please accept answers! XAXA 1569 — 7y
Ad

Answer this question