Format numbers with grouping separators in Lua
How to format numbers with commas or other grouping separators in Lua, what the transformation changes, and when plain digits are the safer choice.
Short answer: useful for display, not for data
Adding grouping separators to a number in Lua makes long values easier to scan, so 1234567.89 can be shown as 1,234,567.89. The decisive tradeoff is that the result is no longer a number. It is a string written for one audience's conventions. Use grouped output in user-facing text such as reports, labels and messages. Keep plain digits wherever the value will be parsed, stored, compared, exported to another program or read by people who use different separator conventions.
What the transformation actually changes
This is a stored character change, not a visual effect. Lua builds a new string with extra characters inserted between digit groups. Nothing about the rendering is altered, and there is no presentation layer that hides the separators from software. Any program that receives the string receives the commas, periods or spaces too. This differs from styling done by a display layer, where the underlying value stays untouched.
Lua has no built-in grouping option. Its string.format accepts only the flags -, +, space, # and 0. It rejects the apostrophe flag that some C libraries use for thousands grouping. os.setlocale does not add grouping either. It can, however, change the decimal point character that C-based number formatting produces, which can surprise code that expects a period. Grouping therefore has to be done with string operations.
The common pattern-loop approach
A widely shared technique repeatedly inserts a comma before the last three digits of the leading integer run until no more replacements happen:
local function comma_value(n)
local formatted = tostring(n)
while true do
local k
formatted, k = formatted:gsub("^(-?%d+)(%d%d%d)", "%1,%2")
if k == 0 then break end
end
return formatted
end
Because the pattern is anchored to the start and the greedy %d+ backtracks, each pass groups one more block from the right. For example, -1234567 becomes -1234,567 and then -1,234,567. The fractional part is never touched. The weakness is tostring itself. In Lua 5.3 and later, tostring(1234.0) gives 1234.0, and large floats can come out in exponent form such as 1e+15, which this loop leaves essentially ungrouped. You also get no control over the number of decimal places.
Another popular variant reverses the digit string, inserts a separator after every three digits, and reverses it back. That works for ASCII digits with a single-byte separator. However, string.reverse operates on bytes, not characters. A multi-byte UTF-8 separator such as a narrow no-break space would have its bytes reversed and come out as invalid text.
A more controlled function
Fixing the precision first and then grouping the integer part avoids both problems. It also lets you choose the separator and decimal point independently:
local function format_number(n, decimals, sep, point)
decimals = decimals or 0
sep = sep or ","
point = point or "."
local s = string.format("%." .. decimals .. "f", n)
local sign, int_part, frac = s:match("^(-?)(%d+)%D?(%d*)$")
if not int_part then
return s -- inf, nan or unexpected output: leave as-is
end
local first = #int_part % 3
if first == 0 then first = 3 end
local groups = { int_part:sub(1, first) }
for i = first + 1, #int_part, 3 do
groups[#groups + 1] = int_part:sub(i, i + 2)
end
local out = sign .. table.concat(groups, sep)
if frac ~= "" then
out = out .. point .. frac
end
return out
end
The match uses %D for the decimal point rather than a literal period. That way it still works if a changed C locale makes string.format emit a comma. The integer part is split from the left, starting with a group of one to three digits, so separators of any byte length are joined safely with table.concat. This code uses only features available since Lua 5.1.
| Call | Expected result |
| format_number(1234567.891, 2) | 1,234,567.89 |
| format_number(-9876543) | -9,876,543 |
| format_number(999) | 999 |
| format_number(1234567.891, 2, ".", ",") | 1.234.567,89 |
| format_number(1234567, 0, "\u{202F}") | 1 234 567 with narrow no-break spaces |
| format_number(math.huge, 2) | returned unchanged; exact text depends on the C library |
These expected results are traced from the documented behavior of string.format and Lua patterns. They were not produced by a test run supplied for this article, so check them in your target Lua version.
Four edge cases are worth knowing:
- Rounding: %f rounds the binary value, so a number like 2.675 may format as 2.67 rather than 2.68.
- Negative zero: a value of -0.0 formats as -0.
- Large integers: in Lua 5.3 and later, %f converts integers to floats, so integers beyond 2^53 lose precision. Format those with %d and group the result instead.
- Older Lua versions: the \u{...} escape requires Lua 5.3 or later. In older versions, write the UTF-8 bytes directly, for example "\226\128\175" for U+202F.
Choosing separators for your readers
Comma grouping with a period decimal point is the US convention, but it is not universal:
- Many European locales use a period or a space for grouping and a comma as the decimal point.
- Swiss conventions often use an apostrophe for grouping.
- Indian numbering groups the last three digits and then pairs of digits, as in 12,34,567. A fixed three-digit function cannot produce this.
- Some style guides prefer a thin or narrow no-break space so the separator cannot be confused with a decimal point.
If your output spans several locales, hard-coded rules become hard to maintain. A binding to a locale data library may be more appropriate than hand-rolled code, but check what is available for your runtime. For single-locale display, the function above is usually enough.
Will the result stay usable after copying or sharing?
- Parsing back: tonumber("1,234") returns nil. Grouped strings cannot be fed back into arithmetic without stripping the separators, and stripping is ambiguous when the separator conventions are unknown.
- CSV and data exchange: a comma separator collides with comma-delimited fields unless quoted. Export plain digits instead.
- Search: someone searching for 1234567 may not match text that reads 1,234,567, depending on the search tool.
- Line breaks: ordinary spaces used as separators can let a number wrap across lines. No-break spaces avoid that, but they are invisible characters that can confuse later editing or exact-match comparisons.
- Byte length: #sep counts bytes, so a UTF-8 space separator is longer than it looks. This matters for fixed-width layouts.
Accessibility is a gap in the available evidence. No documentation or scoped testing of specific screen readers was supplied. How a given assistive technology announces grouped numbers, especially with period or space separators, should be checked in the target environment rather than assumed.
When plain digits are the better choice
- Values written to files, databases, logs meant for machine parsing, or configuration
- Numbers passed to other programs, APIs or spreadsheets that apply their own formatting
- Audiences whose separator conventions you do not know
- Identifiers that happen to be numeric, such as order numbers, codes or years, where grouping would change their meaning
A practical rule is to keep the numeric value as the source of truth and generate the grouped string only at the point of display. If you need to share the number in a form people can also process, provide the plain-digit version alongside the grouped one.