33

I want to make sure a float in PHP is rounded up if any decimal is present, without worrying about mathematical rounding rules. This function would work as follows:

1.1 to 2
1.2 to 2
1.9 to 2
2.3 to 3
2.8 to 3

I know the round() function exists but I don't see any function for rounding up if any decimal is found. Is there any easy way to do this?

serraosays
  • 7,163
  • 3
  • 35
  • 60
Sotiris
  • 38,986
  • 11
  • 53
  • 85

5 Answers5

65

Use the ceil function:

$number = ceil(1.1); //2
ircmaxell
  • 163,128
  • 34
  • 264
  • 314
  • 3
    Sometimes `ceil` (or `floor`) is not the right answer for rounding. You can easily get a calculation result that will behave unexpectedly: `ceil((0.1 + 0.2) * 10)` produces `4`! – Walf Sep 05 '17 at 03:56
23

I know this is an old topic, however it appears in Google. I will extend Blake Plumb's answer regarding precision.

ceil(1024.321 * 100) / 100;

Multiplying by 100 and dividing by 100 only works with one-hundredths. This isn't accurate on tenths, one-thousandths, one-hundred thousandths, etc.

function round_up($number, $precision = 2)
{
    $fig = pow(10, $precision);
    return (ceil($number * $fig) / $fig);
}

Results:

var_dump(round_up(1024.654321, 0)); // Output: float(1025)
var_dump(round_up(1024.654321, 1)); // Output: float(1024.7)
var_dump(round_up(1024.654321, 2)); // Output: float(1024.66)
var_dump(round_up(1024.654321, 3)); // Output: float(1024.655)
var_dump(round_up(1024.654321, 4)); // Output: float(1024.6544)
var_dump(round_up(1024.654321, 5)); // Output: float(1024.65433)
var_dump(round_up(1024.654321, 6)); // Output: float(1024.654321)

Notes:

Thanks for the contributions from Joseph McDermott and brandom for improving my original snippet.

Ash
  • 3,242
  • 2
  • 23
  • 35
13

The official Ceil function will do that for you.

Taken from the example:

<?php
echo ceil(4.3);    // 5
echo ceil(9.999);  // 10
echo ceil(-3.14);  // -3
?>
user2342558
  • 5,567
  • 5
  • 33
  • 54
lethalMango
  • 4,433
  • 13
  • 54
  • 92
10

I know this question has long since been answered, but it came up when I did a google search on the topic. If you want to round up with precision, then a good method would be to use the ceil function and times the number by how many decimal points you want to represent and then divide by that number.

ceil(1024.321*100)/100

would produce 1024.33

Blake Plumb
  • 6,779
  • 3
  • 33
  • 54
3

I like Ash's response, although I would have:

$fig = (int) str_pad('1', $precision + 1, '0');

Makes sense that if I provide precision '2', I would expect it rounded to 2 decimal places. Matter of choice though I suppose. Thanks for the answer Ash, works well.

Robert
  • 5,278
  • 43
  • 65
  • 115
Joseph McDermott
  • 392
  • 3
  • 12