write a function in luau that separates thousands in a number with commas
- User
write a function in luau that separates thousands in a number with commas
Assistant
Here's a Luau function that formats a number with commas separating thousands:
local function formatNumberWithCommas(number) -- Convert the number to a string local formatted = tostring(number) -- Find the position of the decimal point if it exists local decimalPos = formatted:find("%.") -- Separate the integer and decimal parts local integerPart, decimalPart if decimalPos then integerPart = formatted:sub(1, decimalPos - 1) decimalPart = formatted:sub(decimalPos) else integerPart = formatted decimalPart = "" end -- Add commas to the integer part local result = "" local length = #integerPart for i = 1, length do local char = integerPart:sub(i, i) result = result .. char -- Add comma every 3 digits, but not at the end if (length - i) % 3 == 0 and i ~= length then result = result .. "," end end -- Combine with decimal part return result .. decimalPart end -- Example usage: print(formatNumberWithCommas(1234567.89)) -- Output: 1,234,567.89 print(formatNumberWithCommas(1000)) -- Output: 1,000 print(formatNumberWithCommas(123)) -- Output: 123 print(formatNumberWithCommas(123456789)) -- Output: 123,456,789
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.