Using string.format()
(which supposedly defers to C's sprintf()
)) to format a number in LuaJIT rounds differently than every other Lua interpreter I've tried:
$ lua -v
Lua 5.4.1 Copyright (C) 1994-2020 Lua.org, PUC-Rio
$ lua -e 'print(string.format("%.4f", 32.90625))'
32.9062
$ luajit -v
LuaJIT 2.1.0-beta3 -- Copyright (C) 2005-2020 Mike Pall. http://luajit.org/
$ luajit -e 'print(string.format("%.4f", 32.90625))'
32.9063
Why does this happen and how can I make it stop? I'd like to tell LuaJIT to round the same direction every other Lua interpreter does.
I'd like to tell LuaJIT to round
- Implement your ownstring.format
in LuaJIT FFI by invoking standard functionsprintf
as vanilla Lua does. – Unrealitydo local lambda=function(f) return f-0.00001 end print(string.format('%.4f',lambda(32.90625))) end
– Worcester__index
metamethod and write a more precise lambda function to addmath.f_floor()
? Try to see what i mean:do float=32.90625 debug.setmetatable(float,{__index=math}) print(float:floor()) end
– Worcesterelse if (prec < 13) { /* Precision is sufficiently low as to maybe require rounding. */
You could floor it, at the required digit, to make them return similar resultsprint( string.format( "%.4f", math.floor( 32.90625 *10000 ) /10000 ) )
– Mallen