Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why does my value return with a decimal value when it is a whole number?

Asked by 7 years ago
player = game.Players.LocalPlayer

function intWithCommas(i)
local str = "" .. i;
    if(i<1000)  then
return "" .. i;
    end
    return intWithCommas(i/1000) .. "," .. string.sub(str,string.len(str)-2)
end 
player.ValuesforData.Experience.Changed:Connect(function()

        script.Parent.Text = intWithCommas(player:WaitForChild("ValuesforData").Experience.Value)
    end) 

I get 1.5,000 Picture : https://cdn.discordapp.com/attachments/271463355783315456/282716888595824640/unknown.png

When the value is 1500. I have no idea why

1 answer

Log in to vote
0
Answered by 7 years ago
Edited 7 years ago

Actually the picture says "1.5,500". You need to round "1.5" down to 1. That is, on line 8, it needs to be math.floor(i / 1000), not just i / 1000.

As for the second half of the number, I recommend using i % 1000 instead of converting it to a string and chopping off some of the characters - much less work. % is the modulus operator, which essentially returns the remainder after integer division. ex, 1234 % 1000 is 234, the remainder after you perform 1234 / 1000.

Other notes:

  • You can use tostring(i) instead of "" .. i.
  • You don't need parentheses around if conditions (see fixed script below)
  • You almost never need semicolons at the end of a statement; it is usually used for multiple statements that are placed on one line, or in the one case they are needed:
func1()
(func2 or func3)()
--Lua doesn't know if that's two different actions, or just this one:
func1()(func2 or func3)()
--so put a semicolon there:
func1();
(func2 or func3)()

Fixed function:

function intWithCommas(i)
    if i<1000 then
        return tostring(i)
    end
    return intWithCommas(math.floor(i/1000)) .. "," .. (i % 1000)
end

Another option is to use Google to see what others have done. This one, for instance, though much more complicated than your function, is also much more powerful. (If you only need this one situation, though, your function is fine.)

Ad

Answer this question