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

Formatting Floats with string.format

Started by Camulorix, 15 January 2015 - 02:01 PM
Camulorix #1
Posted 15 January 2015 - 03:01 PM
I wanted to show only 2 positions after the decimal point. To do that I wrote this little piece of code:

print(string.format("2.2f", percentage))

The problem is, that it prints a number like 87.044352 instead of 87.04. I know that I can round it when multiplying by 100, using math.floor and dividing by 100 but string.format is there for a reason :)/>
Is it possible that ComputerCraft doesn't implement this case? It works fine on my Linux lua shell, though.
SquidDev #2
Posted 15 January 2015 - 04:06 PM
This sort of format string doesn't exist in Lua. The trouble is %e, %f and %g all do the same thing in computer craft (see here). Your best bet is doing: string.format("%f", percentage):sub(1, 5) instead.
Camulorix #3
Posted 15 January 2015 - 08:50 PM
Oops I got a small typo in my code: The % is missing but it exists in LUA:


Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio
> percentage = 87.044352
> print(string.format("2.2f", percentage))
2.2f
> print(string.format("%2.2f", percentage))
87.04
>

And it's explained at http://www.lua.org/pil/20.html
Lyqyd #4
Posted 15 January 2015 - 09:49 PM
You're right that it does exist in Lua, but LuaJ's implementation of the function is broken in this regard. Your best bet is to manually format the string yourself.


local myNumString = tostring(myNum)
if string.match(myNumString, "%.") then
  myNumString = myNumString.."0"
else
  myNumString = myNumString..".00"
end
local myFloatString = string.match(myNumString, "^(%d+%.%d%d)")

You could put this in a function to make it easier to format multiple different numbers.
Camulorix #5
Posted 15 January 2015 - 11:43 PM
Thanks :)/>