Formatting Float Numbers?

Discussions about Coding and Scripting
1337GameDev
Experienced
Posts: 85
Joined: Thu Apr 16, 2020 3:23 pm
Personal rank: GameDev

Formatting Float Numbers?

Post by 1337GameDev » Sat Mar 27, 2021 6:55 am

Is there a way to format floats, for display?
EG:

instead of 1.02672 I can get a string of "1.02" or "1.03" (rounding)

Is there a way to do this easily? I originally thought about iterating through 10, 1, 0.1, 0.01, 0.001 and extracting digits by casting to an integer, but that seems error prone and super slow.

Would it be better to just cast to a string, substring the digits I want (and possibly stop and extract the digit i want and look to the right to round up/down)?

Any ideas?

Buggie
Adept
Posts: 421
Joined: Sat Mar 21, 2020 5:32 am

Re: Formatting Float Numbers?

Post by Buggie » Sat Mar 27, 2021 7:27 am

Code: Select all

local float a;
local float b;

a = 1.02672;

b = int(a*100)/100;
Log("b = " $ b);

b = int(a*100 + 0.5)/100;
Log("b = " $ b);

1337GameDev
Experienced
Posts: 85
Joined: Thu Apr 16, 2020 3:23 pm
Personal rank: GameDev

Re: Formatting Float Numbers?

Post by 1337GameDev » Sat Mar 27, 2021 6:31 pm

When you display floats... it always includes a handful of extra zeros after the decimal, i want to control that. This method will properly "truncate" floats (assuming there isn't any odd floating point math rounding errors) but doesn't format how they are displayed.... eg: 1.00000 vs 1.0, or 01.00, etc.

Buggie
Adept
Posts: 421
Joined: Sat Mar 21, 2020 5:32 am

Re: Formatting Float Numbers?

Post by Buggie » Sat Mar 27, 2021 10:13 pm

If you always get 6 digit after dot then strip from string last few chars.