• 🏆 Texturing Contest #33 is OPEN! Contestants must re-texture a SD unit model found in-game (Warcraft 3 Classic), recreating the unit into a peaceful NPC version. 🔗Click here to enter!
  • It's time for the first HD Modeling Contest of 2024. Join the theme discussion for Hive's HD Modeling Contest #6! Click here to post your idea!

Lua string formatting and decimal places

Status
Not open for further replies.
Level 4
Joined
Jul 31, 2019
Messages
19
Hello!

Has anyone found a good way to print or set tooltips (or any other numbers) to only a certain number of decimal places in Lua yet? The string.format() option always just returns the minimum number it seems to be able to.

Integer math doesn't work super well either as it is prone to floating point issues.

Example: Turn 99.9978434% to 100.00% or 13.5584759% to 13.56%


Thanks!
 
Level 3
Joined
Aug 6, 2019
Messages
74
function NewRound(decimal)
local decimal = math.floor((decimal*100)+0.5)*0.01
return decimal
end

function NewRound1(decimal)
local aa,bb = math.modf(decimal*100);
local cc=string.sub(bb,3,3);
local dd=string.sub(aa,string.len(aa),string.len(aa));
if cc=="5" and dd%2==0 then
print(aa*0.01)
else
print(NewRound(decimal));
end
end

It can help you?
 
Level 4
Joined
Jul 31, 2019
Messages
19
I had been running with something similar to that until I asked. One problem I was facing is that since lua represents things in floating point form all the time, it can't always accurately represent real numbers. Resulting in something similar to below where it's 98.35001 instead of the real representation of 98.35:
upload_2019-9-27_12-40-45.png
 
In Warcraft 3 Lua you have to inser 2% into string.format or os.date.
Like
Lua:
TimerStart(CreateTimer(), 0.0, false, function()
    print(string.format( "%%.2f", 1/3 ))
    print(string.format( "%%.5f", 1/7 ))
    print(string.format( "%%.2f", 1/23 ))
    print(string.format( "%%.2f", 98.3322313145868866465 ))
    print(os.date("%%Y-%%m-%%d"))
end)
 
Level 4
Joined
Jul 31, 2019
Messages
19
Hahahaha of course you do. You are a godsend Tasyen. Most of my UI work is from your tutorials anyway.

You are doing great work, frankly I probably wouldn't have gotten this far without you. I appreciate it.

Edit: Your response worked great. Correctly formats the string.
 
Last edited:
Status
Not open for further replies.
Top