问题
I am working to convert an excel formula to php function. Now I am facing a problem that is round up as the fraction. Please let me explain it:
- (2 * 18)/2.98 = 12.08 but according to my requirement it should be 12.25
- (2 * 18.5)/2.98 = 12.416 but according to my requirement it should be 12.50
- (2 * 18.8)/2.98 = 12.617 but according to my requirement it should be 12.75
In excel, it is done like :
- ceiling(( 2 * 18 )/2.98, 0.25) = 12.25
- ceiling(( 2 * 18.5 )/2.98, 0.25) = 12.50
- ceiling(( 2 * 18.8 )/2.98, 0.25) = 12.75
I tried in PHP. Ceil() and Floor() do not serve the purpose as these 2 shall give output 13 and 12 accordingly.
Another one round() uses these options PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, or PHP_ROUND_HALF_ODD
which does not serve the purpose.
Anyone there to help me?
回答1:
use this function:
function fractionRound($num,$frac) {
return ceil($num/$frac)*$frac;
}
call it this way:
echo fractionRound(( 2 * 18 )/2.98, 0.25);
it will round to the nearest 0.25 it will return 12.25
回答2:
PHP only provides facility to round to a precision, with the options that you found. However, you can do something similar to what you want with a little inventive mathematics and a userland function.
Try:
function roundTo($value, $roundTo = 1)
{
$inverse = 1 / $roundTo;
return round($value * $inverse) / $inverse;
}
See: https://ideone.com/fojMrS
Note that if you want the ceil
or floor
functionality you'll have to create versions of this function for ceil
and floor
, this is just for round
.
回答3:
$YourNumber = 12.08;
$int = $YourNumber * 4;
$int = ceil($int);
echo $YourNumber ." was the start <br>";
echo $int / 4 ." is the answer";
回答4:
function roundQuarters($input)
{
$rm = $input % 0.25;
return $rm == 0 ? $input : $input - $rm + 0.25;
}
This will round the decimal up to the nearest 0.25, if it's also a divisor of 0.25, it'll return the same. Simple.
And you can replace 0.25 to whatever decimal you want or even parameterize that.
来源:https://stackoverflow.com/questions/36324171/round-up-decimal-number-according-to-fraction-in-php