是否有一个特定的函数可以让我在 PHP 中四舍五入到特定的十进制数

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

我有一个数字需要四舍五入到特定的小数点,PHP 中是否有任何函数可以做到这一点?

我需要每个数字(反映金额)都有一个特定的十进制数。 例如:

小数点需要是 25,所以如果我得到 25.50 美元,我需要它是 26 美元。25,如果我得到了 25.10 美元,它需要 25 美元。25.

我检查过 PHP round(), and specifically ceil(), and I've come across ,但我不确定它是否适用于我的情况,因为我需要的是不同的。

有什么想法吗?即使伪代码作为从哪里开始的提示也会对我有所帮助。谢谢!

我想你需要一个自定义函数,像这样:

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);

我针对你的情况修改了

<?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);

寻找demo here

以下 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' 个值作为 2 个独立的实体。

我能想到的一种方法是将小数点前后的数字拆分为 2 个单独的变量并进行相应处理。

<?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;
} 

这是另一种方法:

<?php

function roundUp($number, $decimal=0.25){
    $dollars = floor($number);
    $cents = $number - $dollars;
    if($cents > $decimal) {
        ++$dollars;
    }
    return $dollars + $decimal;
}

echo roundUp(25.50).PHP_EOL;
echo roundUp(25.10);