Brave.
Brave.

Reputation: 33

How do I round a number in lua to a specific decimal digit?

I need a way to round my decimal in lua.

Sometimes my number looks like this:

HP: 0.79200750000001/1.95

When I search for it online, I only find solutions to round it to a whole number, but I don't want to round my variable to 0.00, 1.00, or 2.00, how would I round it to a specific decimal digit?

Code:


health = 1
maxhp = 2

function hp_showcase()
    makeLuaText("hpcounter", "HP: "..health.."/"..maxhp.."", 2250, 30, 350)
    addLuaText("hpcounter")
end

function opponentNoteHit(id, noteData, noteType, isSustainNote)
    hp_showcase();
end

Upvotes: 2

Views: 2048

Answers (1)

Nifim
Nifim

Reputation: 5031

You can define a function that takes in the value to be rounded and the digit position you would like to round to, for this example positions in front of the . are positive and behind are negative so 2 rounds to the nearest 100 and -2 rounds to the nearest 0.01

local value = 0.79200750000001

local function round(number, digit_position) 
  local precision = math.pow(10, digit_position)
  number = number + (precision / 2); -- this causes value #.5 and up to round up
                                     -- and #.4 and lower to round down.

  return math.floor(number / precision) * precision
end

print(value)
print(round(value, -2))
print(round(value, -1))
print(round(value, 0))

Results:

0.79200750000001
0.79
0.8
1

Upvotes: 1

Related Questions