Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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!

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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);
over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report

0

Following axiac's advice mentioned in the comments and following this thread, the best way to deal with floating point numbers in the context of currencies, is to treat the dollars and cents' values as 2 separate entities.

One way I can think of it to split the numbers before and after the decimal into 2 separate variables and process accordingly.

<?php

function customRound($amount){
   $amount = strval($amount);
   if(preg_match('/(\d+)\.?(\d{1,2})?/', $amount, $matches) !== 1){
      throw new \Exception("Invalid amount.");
   }
   $dollars = intval($matches[1]);
   $cents = intval($matches[2] ?? 0);
   if($cents < 10) $cents *= 10;
   if($cents <= 25) return $dollars . ".25";
   return ($dollars + 1) . ".25";
}

$tests = [25.51,25.49,26.25,25.10,25.49];

foreach ($tests as $test){
    echo $test," => ",customRound($test),PHP_EOL;
} 
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!