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:

LUA
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:

LUA
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.

LUA
input = { price = "19.99", quantity = 3, delivery = "4.95" }

Steps

  1. Return subtotal: input.price (text such as "19.99") times input.quantity, as text.
  2. Add total: the subtotal plus input.delivery (also text), as text.
  3. Add display: the total written with decimal.format and 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.