The string.format() library method does not place leading zeros when using the float specifier

Problem

I discovered that the string.format() library method does not include leading zeros when using the float specifier. Basically, if I do something like this:

local rand = Random.new()
local number = rand:NextNumber(0, 9.9999)
local text = string.format("%04.2f", number)
print(text)

The leading zero will not be printed even though it was specified. The documentation states that “Left-pads the number with zeros instead of empty spaces (see Width below).” of which a screenshot is below. The issue happens in both Studio and in a live game.

Additional Information

Parameter Value
Area Engine
Component Other/LUA Scripting Libraries
First Noticed 5 Jan 2024
Frequency Constant
Impact Minor
Annoyance Level Moderate

Considering that I can duplicate this in a live game, Studio plugins and beta features do not apply.

The live game: Bug Demonstrations
Documentation: string.format()

Workaround

I can code a workaround fix this issue, but it would be better if this was fixed. The basic workaround for this issue is below:

local rand = Random.new()
local number = rand:NextNumber(0, 9.9999)
local text = string.format("%04.2f", number)
if number > -10 and number < 10 then
	text = "0" .. text
end
print(text)

Expectations

Based on the documentation, what I expect to happen is that string.format() inserts leading zeros before the number when the 0 flag is issued using the f (float) specifier.

Visuals
Live game:

Studio:

Documentation:

Reproduction Steps

The steps to reproduce this issue is as follows:

  1. Load the attached baseplate file in studio. There is only one script in ServerScriptService.
  2. Run it.
  3. Observe the results in the output window.

Files

Engine - string.format.rbxl (53.3 KB)

1 Like

Very nicely structured report!

This is not likely a bug. In %04.2f, f represents the number as a float, and 4 the minimal overall length of a formatted string (including the dot), not only the int part.

local number = 12.345
local text = string.format("%07.3f", number)
print(text) --> 012.345

Other specifiers, for example, for int representations, work similarly.

local number = 5
local text = string.format("%02i", number)
print(text) --> 05
3 Likes

And that was the issue. Changing it from 4.2 to 5.2 solved it. I posted this in the scripting support and nobody would respond. I don’t like posting bug reports for things that aren’t bugs.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.