How do I fill up a number's decimal places with zeroes?

4.5k views Asked by At

Assume the following numbers:

local a = 2
local b = 3.1
local c = 1.43
local d = 1.0582

My goal is to round these numbers to two decimal places. The result should be this, respectively:

a = 2.00
b = 3.10
c = 1.43
d = 1.06 or 1.05

Obviously I understand that any number with trailing decimal zeroes will get rounded. 2.00 will be 2. But I need the numbers as strings, and to make it visually more appealing, I would need these two decimal places.

Here's a function I use to round to two decimal places:

function round(num, numDecimalPlaces)
local mult = 10^(numDecimalPlaces or 0)
return math.floor(num * mult + 0.5) / mult
end

This works fine for test cases c and d, but will produce wrong results with a and b: it won't fill up with zeroes. I understand it is because the rounding function takes the numbers and calculates them - therefore the excess zeroes get cut off.

But that is exactly not my goal - not cutting them off.

I've tried string manipulation, by checking if and where a . is in a number, but that didn't work at all, for any case. My method:

local zei
if i < 100 then
    if tostring(i):find("%.") == nil then
        zei = round(i, 2) .. ".00" --No decimal point found, append .00
    else
        zei = round(i, 2) --Found decimal point, round to 2
    end
    if tostring(i):find("%.")+2 == tostring(i):len() then
        zei = round(i, 2) .. "0" --Found point, but only one trailing number, append 0
    end
else
    zei = round(i, 0) --Number is over 100, no decimal points needed
end

The above 100 case is just for aesthetics and not relevant here. Where zei is the displayed string, and i is one of the test case numbers.

Summary

How would I round a number to two decimal places, but append trailing zeroes, even if they were excess, e.g. 2.30? I understand I need strings for this.

Contradicting question: Strip off excess zeroes

1

There are 1 answers

1
Nicol Bolas On BEST ANSWER

You don't round numbers. You create string representations of those numbers. That would be done by string.format, with an appropriate format. Like this:

string.format("%.2f", a);