La fonction round en php

[PHP 4, PHP 5, PHP 7, PHP 8]

roundArrondit un nombre à virgule flottante

Description

round[int|float $num, int $precision = 0, int $mode = PHP_ROUND_HALF_UP]: float

Liste de paramètres

num

La valeur à arrondir.

precision

Le nombre optionnel de décimales à arrondir.

Si le paramètre precision est positif, num sera arrondi en utilisant le paramètre precision pour définir le nombre significatif de digits après le point décimal.

Si le paramètre precision est négatif, num arrondi en utilisant le paramètre precision pour définir le nombre significatif de digits avant le point décimal, i.e. le multiple le plus proche de pow[10, -precision], i.e. pour une precision de -1, num sera arrondi à 10, pour une precision de -2 à 100, etc.

mode

Utilisez une des constantes suivantes pour spécifier le mode d'arrondi.

ConstantesDescription
PHP_ROUND_HALF_UP Arrondit num en s'éloignant de zéro lorsqu'il est à mi-chemin, arrondissant ainsi 1.5 à 2, et -1.5 à -2.
PHP_ROUND_HALF_DOWN Arrondit num en se rapprochant de zéro lorsqu'il est à mi-chemin, arrondissant ainsi 1.5 à 1, et -1.5 à -1.
PHP_ROUND_HALF_EVEN Arrondit num à la valeur paire la plus proche lorsqu'il est à mi-chemin, arrondissant ainsi 1.5 et 2.5 à 2.
PHP_ROUND_HALF_ODD Arrondit num à la valeur impaire la plus proche lorsqu'il est à mi-chemin, arrondissant ainsi 1.5 à 1 et 2.5 à 3.

Valeurs de retour

La valeur arrondie à la precision donnée en tant que nombre décimal.

Historique

VersionDescription
8.0.0 num n'accepte plus les objets internes qui supporte les conversions numériques.

Exemples

Exemple #1 Exemple avec round[]

L'exemple ci-dessus va afficher :

float[3]
float[4]
float[4]
float[4]
float[5.05]
float[5.06]
float[300]
float[0]
float[700]
float[1000]

Exemple #2 Comment precision affecte un flottant

L'exemple ci-dessus va afficher :

float[135.79]
float[135.79]
float[135.8]
float[136]
float[140]
float[100]
float[0]

Exemple #3 Exemple avec mode

L'exemple ci-dessus va afficher :

Mode d'arrondi avec 9.5
float[10]
float[9]
float[10]
float[9]

Mode d'arrondi avec 8.5
float[9]
float[8]
float[8]
float[9]

Exemple #4 Exemple avec mode et precision

L'exemple ci-dessus va afficher :

Utilisation de PHP_ROUND_HALF_UP avec une précision d'une décimale
float[1.6]
float[-1.6]

Utilisation de PHP_ROUND_HALF_DOWN avec une précision d'une décimale
float[1.5]
float[-1.5]

Utilisation de PHP_ROUND_HALF_EVEN avec une précision d'une décimale
float[1.6]
float[-1.6]

Utilisation de PHP_ROUND_HALF_ODD avec une précision d'une décimale
float[1.5]
float[-1.5]

Voir aussi

  • ceil[] - Arrondit au nombre supérieur
  • floor[] - Arrondit à l'entier inférieur
  • number_format[] - Formate un nombre pour l'affichage

takingsides at gmail dot com

8 years ago

In my opinion this function lacks two flags:

- PHP_ROUND_UP - Always round up.
- PHP_ROUND_DOWN - Always round down.

In accounting, it's often necessary to always round up, or down to a precision of thousandths.

goreyshi at gmail dot com

4 years ago

When you have a deal with money like dollars, you need to display it under this condition:
-format all number with two digit decimal for cents.
-divide 1000 by ,
-round half down for number with more than two decimal

I approach it using round function inside the number_format function:

number_format[[float]round[ 625.371 ,2, PHP_ROUND_HALF_DOWN],2,'.',',']  // 625.37
number_format[[float]round[ 625.379 ,2, PHP_ROUND_HALF_DOWN],2,'.',',']  // 625.38
number_format[[float]round[ 1211.20 ,2, PHP_ROUND_HALF_DOWN],2,'.',',']  // 1,211.20
number_format[[float]round[ 625 ,2, PHP_ROUND_HALF_DOWN],2,'.',',']      // 625.00

depaula at unilogica dot com

5 years ago

As PHP doesn't have a a native number truncate function, this is my solution - a function that can be usefull if you need truncate instead round a number.



Originally posted in //stackoverflow.com/a/12710283/1596489

slimusgm at gmail dot com

8 years ago

If you have negative zero and you need return positive number simple add +0:

$number = -2.38419e-07;
var_dump[round[$number,1]];//float[-0]
var_dump[round[$number,1] + 0];//float[0]

serg at kalachev dot ru

8 years ago

Excel-like ROUNDUP function:

public static function round_up[$value, $places]
{
    $mult = pow[10, abs[$places]];
     return $places < 0 ?
    ceil[$value / $mult] * $mult :
        ceil[$value * $mult] / $mult;
}

echo round_up[12345.23, 1]; // 12345.3
echo round_up[12345.23, 0]; // 12346
echo round_up[12345.23, -1]; // 12350
echo round_up[12345.23, -2]; // 12400
echo round_up[12345.23, -3]; // 13000
echo round_up[12345.23, -4]; // 20000

djcox99 at googlemail dot com

8 years ago

I discovered that under some conditions you can get rounding errors with round when converting the number to a string afterwards.

To fix this I swapped round[] for number_format[].

Unfortunately i cant give an example [because the number cant be represented as a string !]

essentially I had round[0.688888889,2];

which would stay as 0.68888889 when printed as a string.

But using number_format it correctly became 0.69.

Hayley Watson

3 years ago

It should just be noted that what is called "precision" on this page is more correctly called accuracy; precision is the total number of significant digits on both sides of the decimal point, while accuracy is the number of digits to the right of the point. It's a common confusion.

greghenle at gmail dot com

5 years ago

/**
* Round to first significant digit
* +N to +infinity
* -N to -infinity
*
*/
function round1stSignificant [ $N ] {
  if [ $N === 0 ] {
    return 0;
  }

  $x = floor [ log10 [ abs[ $N ] ] ];

  return [ $N > 0 ]
    ? ceil[ $N * pow [ 10, $x * -1 ] ] * pow[ 10, $x ]
    : floor[ $N * pow [ 10, $x * -1 ] ] * pow[ 10, $x ];
}

echo round1stSignificant[ 39144818 ] . PHP_EOL;
echo round1stSignificant[ 124818 ] . PHP_EOL;
echo round1stSignificant[ 0.07468 ] . PHP_EOL;
echo round1stSignificant[ 0 ] . PHP_EOL;
echo round1stSignificant[ -0.07468 ] . PHP_EOL;

/**
* Output
*
* 40000000
* 200000
* 0.08
* 0
* -0.08
*
*/

Mojo urk

4 years ago

Solving round_down[] problem:
-----------------------------
Use of fails in some cases, e.g. round_down[2.05, 2] gives incorrect 2.04.
Here is a "string" solution [//stackoverflow.com/a/26491492/1245149] of the problem [a negative precision is not covered]:



Solving round_up[] problem:
---------------------------
Use of fails in some cases, e.g. round_up[2.22, 2] gives incorrect 2.23 [//stackoverflow.com/a/8239620/1245149].
Adapting the above round_down[] "string" solution I have got this result [a negative precision is not covered]:



I don't know it is bulletproof, but at least it removes the above mentioned fail. I have done no binary-to-decimal-math-analysis but if `$floorValue + pow[10, 0 - $precision]` works
always as expected then it should be ok.

jongbumi at gmail dot com

6 years ago

PHP 5.3, 5.4, 5.5


PHP 5.6


PHP 7

dastra

10 years ago

round[] will sometimes return E notation when rounding a float when the amount is small enough - see  //bugs.php.net/bug.php?id=44223 .  Apparently it's a feature.

To work around this "feature" when converting to a string, surround your round statement with an sprintf:

sprintf["%.10f", round[ $amountToBeRounded, 10]];

craft at ckdevelop dot org

8 years ago

function mround[$val, $f=2, $d=6]{
    return sprintf["%".$d.".".$f."f", $val];
}

echo mround[34.89999];  //34.90

twan at ecreation dot nl

22 years ago

If you'd only want to round for displaying variables [not for calculating on the rounded result] then you should use printf with the float:



This returns: 3.40 .

Anonymous

11 years ago

Here is function that rounds to a specified increment, but always up. I had to use it for price adjustment that always went up to $5 increments.

esion99 at gmail dot com

8 years ago

Unexpected result or misunderstanding [php v5.5.9]

christian at deligant dot net

11 years ago

this function [as all mathematical operators] takes care of the setlocale setting, resulting in some weirdness when using the result where the english math notation is expected, as the printout of the result in a width: style attribute!

michaeldnelson dot mdn at gmail dot com

12 years ago

This function will let you round to an arbitrary non-zero number.  Zero of course causes a division by zero.

martinr at maarja dot net

14 years ago

Please note that the format of this functions output also depends on your locale settings. For example, if you have set your locale to some country that uses commas to separate decimal places, the output of this function also uses commas instead of dots.

This might be a problem when you are feeding the rounded float number into a database, which requires you to separate decimal places with dots.

See it in action:


The output will be:
3.56
3,56

php at silisoftware dot com

20 years ago

Here's a function to round to an arbitary number of significant digits. Don't confuse it with rounding to a negative precision - that counts back from the decimal point, this function counts forward from the Most Significant Digit.

ex:



Works on negative numbers too. $sigdigs should be >= 0

feha at vision dot to

12 years ago

Here is a short neat function to round minutes [hour] ...



You decide to round to nearest minute ...
example will produce : 14:05

Anonymous

5 years ago

Note that PHP 5.3 didn't just introduce $mode, it rewrote the rounding implementation completely to eliminate many kinds of rounding errors common to rounding floating point values.

That's why round[] gives you the correct result even when floor/ceil don't.
For example,  floor[0.285 * 100 + 0.5] VS round[0.285*100 + 0.5]. First one gives 28, second one gives 29.

More details here: //wiki.php.net/rfc/rounding

terry at scribendi dot com

18 years ago

To round any number to a given number of significant digits, use log10 to find out its magnitude:



Or when you have to display a per-unit price which may work out to be less than a few cents/pence/yen you can use:



This always displays at least the number of decimal places required by the currency, but more if displaying the unit price with precision requires it - eg: 'English proofreading from $0.0068 per word', 'English beer from $6.80 per pint'.

omnibus at omnibus dot edu dot pl

11 years ago

Beware strange behaviour if number is negative and precision is bigger than the actual number of digits after comma.

round[-0.07, 4];

returns

-0.07000000000000001

So if you validate it against a regular expression requiring the maximum amount of digits after comma, you'll get into trouble.

Anonymous

12 years ago

This functions return ceil[$nb] if the double or float value is bigger than "$nb.5" else it's return floor[$nb]

spectrumcat at gmail dot com

8 years ago

In case someone will need a "graceful" rounding [that changes it's precision to get a non 0 value] here's a simple function:

function gracefulRound[$val, $min = 2, $max = 4] {
    $result = round[$val, $min];
    if [$result == 0 && $min < $max] {
        return gracefulRound[$val, ++$min, $max];
    } else {
        return $result;
    }
}

Usage:
$_ = array[0.5, 0.023, 0.008, 0.0007, 0.000079, 0.0000048];
foreach [$_ as $val] {
    echo "{$val}: ".gracefulRound[$val]."\n";
}

Output:
0.5: 0.5
0.023: 0.02
0.008: 0.01
0.0007: 0.001
0.000079: 0.0001
0.0000048: 0

maxteiber at gmail dot com

15 years ago

the result of this function always depends on the underlying C function. There have been a lot of compiler bugs and floating-point precission problems involving this function. Right now the following code:



returns:

141.07

on my machine.
So never really trust this function when you do critical calculations like accounting stuff!
Instead: use only integers or use string comparisons.

Anonymous

5 years ago

This function has strange. behaviors:



If I round this:



You can also use a ceil [which might be useful for pagination]:



[Edited by: for clarity]

php at persignum dot com

7 years ago

Because this function is missing round up and round down constants and the top note doesn't really show you how to round up or down to the nearest number, here is an easy way to always round up or always round down to the nearest number.

int is the number you want to round

n is the nearest number you want rounded to.

Round up to the nearest number

function round_up[$int, $n] {
    return ceil[$int / $n] * $n;
}

And to round down to the nearest number

function round_down[int, $n] {
    return floor[$int / $n] * $n;
}

Bevan

13 years ago

Formats a number to the specified number of significant figures.

Chủ Đề