Is there a function in lua similar to parseFloat()

I have a volume gui thing in my game, and I’d just like the number of the volume to be a float instead of just an integer, because having a 5 instead of a 5.0 is weirdly bothering me.

I could always just use string manipulation to get it, but I’m wondering if there’s an easier way.

This will round to the nearest number

math.floor(num + 0.5) 
1 Like

parseFloat() turns a number into a float.

1 Like

I meant like, is there a way to turn the integer “5” into the float “5.0”

I just realised I read the question wrong!

2 Likes

Sadly that’s not a lua function as far as I’m aware of.

Yep, I’m just telling him what you meant since he didn’t answer your question. If you just want to tack on .0 if there’s no fractional part, you can check if math.modf returns a second number and, if not, concatenate .0 to the end. Example:

local function toFloat(number)
     local int, frac = math.modf(number)
     if frac == 0 then
        return int .. ".0" -- if there's no fractional part then shove on .0 
    end

    return number -- if it returns frac it's already a float.
end

It might be better to use string manipulation, but this is probably the closest you can get without using that.

1 Like

yeah, found this on stackoverflow

Lua has a single numerical type, Lua numbers. There is no distinction between integers and floats. So we always convert Lua numbers into integer replies, removing the decimal part of the number if any. If you want to return a float from Lua you should return it as a string , exactly like Redis itself does (see for instance the ZSCORE command).

So no wonder I was having trouble with it lol

1 Like

For those interested, the string method is as follows:

function floatify(number)
    return string.format("%0.1f", number)
end

Where the 1 represents how many decimal places to truncate(?) to.

5 Likes

that’s really simple I’m annoyed now :laughing:

To simplify it further, you could do this:

-- At the top of your script:
local toFloat = '%f'

-- To output a float:
toFloat:format(5)

A string like ‘%.5f’ does tell Lua to truncate the output to 5 decimal places
Edit: sorry, didn’t mean to make that a reply to you

3 Likes