Learn Lua · Numbers and text · Lesson 1 of 4
Money with decimals
Ordinary numbers can't hold most decimal fractions exactly, so sums of money drift by
tiny amounts. A decimal is exact. Make one from text with decimal.new, and use the
usual operators:
local price = decimal.new("19.99")
tostring(price * 3) --> "59.97"
tostring(price * 3 + decimal.new("4.95")) --> "64.92"decimal.format writes a decimal for people to read. Its options go in a table, such as
the currency symbol:
decimal.format(decimal.new("64.92"), { symbol = "$" }) --> "$64.92"In the Input line, integer means a whole number.
What your code receives
Your code gets its data as input. The type Input line at the top of the code lists every field, and the editor uses it to suggest field names and spot typos. Here is an example. Each check sends different values, so work from the fields rather than these exact values.
input = { price = "19.99", quantity = 3, delivery = "4.95" }Steps
- Return
subtotal:input.price(text such as"19.99") timesinput.quantity, as text. - Add
total: the subtotal plusinput.delivery(also text), as text. - Add
display: the total written withdecimal.formatand the symbol"£".
Show a hint
Turn the text into a decimal before you multiply. Keep the subtotal and total as decimals
in locals, and turn them into text only in the return.