This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
rockymc's profile picture

string.format("%.3f") not formatting float object

Started by rockymc, 25 May 2015 - 08:21 PM
rockymc #1
Posted 25 May 2015 - 10:21 PM
I was messing with a program I made, when I realized that when I tried to format a float, the float wouldn't format.

Then, I opened the in-game lua and typed this

print(string.format("%.3f", 3.14159))
And the result was 3.14159 instead of 3.141 (3.142 because it rounds the number).

Is it a known issue? What can I do to fix it?
Edited on 25 May 2015 - 08:24 PM
Creator #2
Posted 25 May 2015 - 10:38 PM
Maybe, use a string.
Anavrins #3
Posted 25 May 2015 - 10:45 PM
It is known and I believe it's an issue with LuaJ,
Here's a workaround

local function round(num, dec)
  local shift = 10^(dec or 2)
  return math.floor(num * shift + 0.5) / shift
end
round(math.pi) -> 3.14
round(math.pi, 4) -> 3.1416
Lyqyd #4
Posted 25 May 2015 - 10:59 PM
Known issue with LuaJ.