Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

php - Rounding to nearest fraction (half, quarter, etc.)

So, I need to create the following functions but my head can't think of any possibility in PHP without complicated math.

  • Round always up to the nearest decimal (1.81 = 1.90, 1.89 = 1.90, 1.85 = 1.90)
  • Round always down to the nearest decimal (1.81 = 1.80, 1.89 = 1.80, 1.85 = 1.80)
  • Round always up to the nearest x.25 / x.50 / x.75 / x.00 (1.81 = 2, 1.32 = 1.50)
  • Round always down to the nearest x.25 / x.50 / x.75 / x.00 (1.81 = 1.75, 1.32 = 1.25)
  • Round always up to the nearest x.50 / 1 (1.23 = 1.50, 1.83 = 2)
  • Round always down to the nearest x.50 / 1 (1.23 = 1, 1.83 = 1.50)

I have searched on Google for 2 hours now and the only things that came up were Excel forums. Is it possible with some simple lines of PHP?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since you're looking for fourths (.00, .25, .50, .75), multiply your number by 4, round to nearest whole number as desired (floor if down, ceil if up), then divide by 4.

1.32, down to nearest fourth:

1.32 * 4 = 5.28
floor(5.28) = 5.00
5.00 / 4 = 1.25

Same principle applies for any other fractions, such as thirds or eighths (.0, .125, .25, .375, .5, .625, .75, .875). For example:

1.77, up to nearest eighth:

1.77 * 8 = 14.16
ceil(14.16) = 15.00
15.00 / 8 = 1.875


Just for fun, you could write a function like this:

function floorToFraction($number, $denominator = 1)
{
    $x = $number * $denominator;
    $x = floor($x);
    $x = $x / $denominator;
    return $x;
}

echo floorToFraction(1.82);      // 1
echo floorToFraction(1.82, 2);   // 1.5
echo floorToFraction(1.82, 3);   // 1.6666666666667
echo floorToFraction(1.82, 4);   // 1.75
echo floorToFraction(1.82, 9);   // 1.7777777777778
echo floorToFraction(1.82, 25);  // 1.8

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...