Rounding to 1 decimal point

Im basically making a speed gun system for my game, but once I get the result I get ridiculous numbers with 20 or so decimal digits, is it possible to round it down to just 1? I’ve seen people use math.floor but as far as I know it rounds it to the nearest whole number where as I need to it to round to round to 1 decimal, for example:

local x = 4.6787673219385

function Round(Number)
return math.floor(Number)
end

print(Round(x))

This would return 5, I need it to return 4.6 or 4.7 instead

13 Likes

use string.format:

function roundNumber(num, numDecimalPlaces)
  return tonumber(string.format("%." .. (numDecimalPlaces or 0) .. "f", num))
end

print(roundNumber(4.6787673219385, 1)) --prints 4.7
print(roundNumber(4.6787673219385, 2)) --prints 4.68
print(roundNumber(4.6787673219385, 3)) --prints 4.679
58 Likes

Alternatively you can multiply by 10 then round the value then divide it by 10.

function round(num)
  return math.floor(num * 10) / 10;
end;
print(round(4.6787673219385)) --> 4.7
30 Likes

How will I get 4.6 instead so I can show the player that he has 4.6+ instead of 4.7+ which he doesn’t?

You don’t need the semi-colon, by the way.

Edit: Solved by subtracting .05.

this does not work if there is a 0 at the end. For example, if the number starting is 4.0193, it will only output “4”, not “4.0”
How do we get this 0 to stay on the end?

1 Like

Just don’t add the tonumber in that function. Also, you shouldn’t reply to a post that is already 3 years old.

Code:

function roundNumber(num, numDecimalPlaces)
  return string.format("%." .. (numDecimalPlaces or 0) .. "f", num)
end

print(roundNumber(4.6787673219385, 1)) --prints 4.7
print(roundNumber(4.6787673219385, 2)) --prints 4.68
print(roundNumber(4.6787673219385, 3)) --prints 4.679

Keep in mind this function now returns a string instead of a number.

1 Like