Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a specific function that allows me to round up to a specific decimal number in PHP

Tags:

php

rounding

I have a number that needs to be rounded up to a specific decimal, is there any function in PHP to do that?

I need every number (which reflects an amount of money) to have a specific decimal number. For example:

The decimal needs to be 25, so if I got $ 25.50 I need it to be $ 26.25, and if I got $ 25.10 it needs to be $ 25.25.

I've checked PHP round(), and specifically ceil(), and I've come across this answer in Python, but I'm not sure it applies to my case, because what I need is different.

Any ideas? Even pseudo code as a tip on where to start will help me. Thanks!

like image 503
Rosamunda Avatar asked Nov 18 '25 01:11

Rosamunda


2 Answers

I think you need a custom function, something like this:

function my_round($number, $decimal = 0.25) {
  $result = floor($number) + $decimal;
  if ($result < $number) $result = ceil($number) + $decimal;
  return $result;
}

print my_round(25.50);
like image 122
PlayerKillerYKT Avatar answered Nov 20 '25 16:11

PlayerKillerYKT


I modified this answer for your case:

<?php
function roundUp($number){
    $int = floor($number);
    $float = $number-$int;
    if ($float*10 < 2.5)
        $result = $int;
    else
        $result = ceil($number);
    $result+= 0.25;
    echo $number." becomes ".$result."\n";
}

roundUp(25.50);
roundUp(25.10);

Look for demo here

like image 34
adampweb Avatar answered Nov 20 '25 17:11

adampweb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!