Open In App

How to Round Number to n Decimal Places in PHP ?

Last Updated : 17 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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;
  
// Round to 2 decimal places
$roundNumber = round($number, 2);
  
echo "Original Number: " . $number . "\n";
echo "Rounded Number: " . $roundNumber;
  
?>


Output

Original Number: 3.14159
Rounded Number: 3.14

Using number_format() Function

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;
  
// Round to 2 decimal places
$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;
  
// Round to 2 decimal places
$roundNumber = sprintf("%.2f", $number);
  
echo "Original Number: " . $number . "\n";
echo "Rounded Number: " . $roundNumber;
  
?>


Output

Original Number: 3.14559
Rounded Number: 3.15


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads