Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round DOWN to nearest half integer in PHP

Tags:

php

I need a PHP function that will take a float and round it down to the nearest half (x.0 or x.5). I found other functions that will round to the nearest fraction, but they round both ways.

The function I need can only round down.

Examples

7.778 -> 7.5

7.501 -> 7.5

7.49 -> 7.0

7.1 -> 7.0

like image 211
Chris Fletcher Avatar asked Jul 09 '10 20:07

Chris Fletcher


People also ask

How do you round to the nearest half integer?

When rounding to the nearest half, round the fraction to whichever half the fraction is closest to on the number line. If a fraction is equally close to two different halves, round the fraction up. Here is a fraction. To figure out which value five-sixths is closest to, first think in terms of sixths.

How do you round down in PHP?

The floor() function rounds a number DOWN to the nearest integer, if necessary, and returns the result. Tip: To round a number UP to the nearest integer, look at the ceil() function. Tip: To round a floating-point number, look at the round() function.

How can I limit float to 2 decimal places in PHP?

What's the correct way to round a PHP string to two decimal places? $number = "520"; // It's a string from a database $formatted_number = round_to_2dp($number); echo $formatted_number; The output should be 520.00 ; How should the round_to_2dp() function definition be?


2 Answers

$x = floor($x * 2) / 2; 
like image 139
Dominic Rodger Avatar answered Sep 21 '22 19:09

Dominic Rodger


I'm assuming PHP has a floor function: floor($num * 2) / 2 ought to do it.

like image 27
tzaman Avatar answered Sep 21 '22 19:09

tzaman