How to Round Number to n Decimal Places in PHP ?
Last Updated :
17 Jan, 2024
Rounding numbers to a specific decimal place is a common operation in programming, especially when dealing with precision in mathematical calculations. PHP provides several approaches to achieve this rounding.
Using round() Function
The round() function is a built-in PHP function that rounds a number to the nearest integer or a specified number of decimal places.
PHP
<?php
$number = 3.14159;
$roundNumber = round ( $number , 2);
echo "Original Number: " . $number . "\n" ;
echo "Rounded Number: " . $roundNumber ;
?>
|
Output
Original Number: 3.14159
Rounded Number: 3.14
The number_format() function is used to formatting numbers as strings with grouped thousands. However, it can also be utilized to round numbers to a specific number of decimal places.
PHP
<?php
$number = 3.14559;
$roundNumber = number_format( $number , 2);
echo "Original Number: " . $number . "\n" ;
echo "Rounded Number: " . $roundNumber ;
?>
|
Output
Original Number: 3.14559
Rounded Number: 3.15
Using sprintf() Function
The sprintf() function is used to formatting strings, and it can also be employed for rounding numbers to a specific number of decimal places.
PHP
<?php
$number = 3.14559;
$roundNumber = sprintf( "%.2f" , $number );
echo "Original Number: " . $number . "\n" ;
echo "Rounded Number: " . $roundNumber ;
?>
|
Output
Original Number: 3.14559
Rounded Number: 3.15
Share your thoughts in the comments
Please Login to comment...