Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do you make sure a number/string always has 2 decimal places?

I'm working on a free ticket printing machine which means I need to store money values. The problem is that if I buy a ticket priced 2.50 then Roblox displays that as "2.5". That's fine for the internal math bit but when I'm displaying the balance on the screen I want it to always have 2 decimal places.

--The balance is 100
local ticketPrice = 2.5

local balance = tonumber(Hit.Parent.balance.Value)
local balanceRemains = balance - ticketPrice
local balanceRemainsString = tostring(balanceRemains)
--Currently this would output 97.5 but I'm trying to get it to output 97.50

I've been looking at rounding and stuff but I can't find articles that are about money, most people want to round multiple decimal places into fewer but I don't have multiple. Thanks for the help!

1 answer

✓ Accepted answer

I made a function that uses some string functions like string.find. The main thing to note is that since you want 2 decimal places, you would check if there's a period or not, then fill the rest in. Please ask me questions.

local To2Decimals = function(String)
	
	String = tostring(tonumber(String)); -- checking if it's a number. it would error if it isnt.
	-- also turning it into a number then to a string makes the number into its simplist form, instead of
	-- 1.00 you get 1
	
	
	local Period = string.find(String,'%.'); --finding the period, since you wanted 2 decimal places. Note that i also placed a % cuz string patterns. the period alone in a string pattern means any character.
	
	if not Period then 
		-- if theres no period it would suggest that the number is a whole number and all whole numbers with 2
		-- decimal places end in ".00"
		return String..'.00';
	end;

	local Cents = String:sub(Period+1);-- getting cents
	if #Cents==1 then --note: #(string) is the same thing as string.len
		-- this checks if theres one decimal place, if so then add a 0
		return String..'0'
	end;
	return String; -- returns the string itself if it has more than 1 decimal place
end;


print(
	'a = '..To2Decimals('1')..'\n',
	'b = '..To2Decimals('2.5')..'\n',
	'c = '..To2Decimals('3.75')..'\n'
)

1 comment

0

Thank you this works perfectly!

This discussion is preserved as it was. New answers, comments, and votes are closed.