Michał Wiatr
Michał Wiatr

Reputation: 481

Rounding up to the multiple of float number in PHP

I want to round number to the specific number or to a multiple of them. For integer it is ok, but problem appears when I want round to the multile of float like this example:

Number (or multiple) of package I want to round:

2.6

When I type 1 it should round up to 2.6

When I type 2,5 it should round up to 2,6

When I type 3 it should round up to 5,2 (2 * 2,6)

I tried to use fmod to check divisibility but it is not working for me.

Thanks all.

Upvotes: 2

Views: 589

Answers (1)

Justin L.
Justin L.

Reputation: 13600

You could just divide your number by your base float, round it up to the nearest int, and re-multiply.

psuedo code

def round_to_float(base_float,to_round)
    return ceiling(to_round / base_float) * base_float
end

example with 3:

ceiling(3.0 / 2.6) * 2.6
ceiling(1.15) * 2.6
2 * 2.6
5.2

For multiple checking, you could use fmod($to_round,$base_float) == 0, but there will inevitably be floating point inaccuracies and it's not a reliable way to test floats.

To be certain, you should pick a small enough epsilon (on the order of machine precision on your computer), and make sure your quotient to_round/base_float is within epsilon of its floor.

putting it all together

def round_to_float(base_float,to_round)
    quotient = to_round / base_float
    if (absolute_value(quotient - floor(quotient)) < epsilon)
        return false
    else
        return ceiling(quotient) * base_float
    end
end

where epsilon is a really small number. In theory it should be your machine precision ... usually something like 10^-9. In practice 10^-4 should be sufficient in most use cases.

Upvotes: 3

Related Questions