Page 1 of 1

round() function [ PHP ]

Posted: Thu Dec 12, 2024 10:28 pm
by CoDeR
It is a function used to round decimal numbers. It is included in PHP mathematics. Its usage is as follows:

Code: Select all

round(10.2986108,  2);
Expected output:
10.29

Use of mods

PHP_ROUND_HALF_UP sayı yarı yolda olduğunda sıfırdan uzaklaştırır, 1,5'i 2'ye ve -1,5'i -2'ye yuvarlar.
PHP_ROUND_HALF_DOWN sayı yarı yolda olduğunda sıfıra doğru yuvarlar, 1,5'i 1'e ve -1,5'i -1'e yuvarlar.
PHP_ROUND_HALF_EVEN sayı yarı yolda olduğunda en yakın çift değere doğru yuvarlar, hem 1,5'i hem de 2,5'i 2'ye yuvarlar.
PHP_ROUND_HALF_ODD sayı yarı yolda olduğunda en yakın tek değere doğru yuvarlar, 1,5'i 1'e ve 2,5'i 3'e yuvarlar.
Example

Code: Select all

<?php
echo 'Rounding modes with 9.5' . PHP_EOL;
var_dump(round(9.5, 0, PHP_ROUND_HALF_UP));
var_dump(round(9.5, 0, PHP_ROUND_HALF_DOWN));
var_dump(round(9.5, 0, PHP_ROUND_HALF_EVEN));
var_dump(round(9.5, 0, PHP_ROUND_HALF_ODD));

echo PHP_EOL;
echo 'Rounding modes with 8.5' . PHP_EOL;
var_dump(round(8.5, 0, PHP_ROUND_HALF_UP));
var_dump(round(8.5, 0, PHP_ROUND_HALF_DOWN));
var_dump(round(8.5, 0, PHP_ROUND_HALF_EVEN));
var_dump(round(8.5, 0, PHP_ROUND_HALF_ODD));
?>
Expected output:

Code: Select all

Rounding modes with 9.5
float(10)
float(9)
float(10)
float(9)

Rounding modes with 8.5
float(9)
float(8)
float(8)
float(9)
Example # mode with precision examples

Code: Select all

<?php
echo 'Using PHP_ROUND_HALF_UP with 1 decimal digit precision' . PHP_EOL;
var_dump(round( 1.55, 1, PHP_ROUND_HALF_UP));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_UP));

echo PHP_EOL;
echo 'Using PHP_ROUND_HALF_DOWN with 1 decimal digit precision' . PHP_EOL;
var_dump(round( 1.55, 1, PHP_ROUND_HALF_DOWN));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_DOWN));

echo PHP_EOL;
echo 'Using PHP_ROUND_HALF_EVEN with 1 decimal digit precision' . PHP_EOL;
var_dump(round( 1.55, 1, PHP_ROUND_HALF_EVEN));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_EVEN));

echo PHP_EOL;
echo 'Using PHP_ROUND_HALF_ODD with 1 decimal digit precision' . PHP_EOL;
var_dump(round( 1.55, 1, PHP_ROUND_HALF_ODD));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_ODD));
?>
Expected Output

Code: Select all

Using PHP_ROUND_HALF_UP with 1 decimal digit precision
float(1.6)
float(-1.6)

Using PHP_ROUND_HALF_DOWN with 1 decimal digit precision
float(1.5)
float(-1.5)

Using PHP_ROUND_HALF_EVEN with 1 decimal digit precision
float(1.6)
float(-1.6)

Using PHP_ROUND_HALF_ODD with 1 decimal digit precision
float(1.5)
float(-1.5)