PHP format number with 2 decimals example

In this tutorial will give you an example of PHP format number with 2 decimals. You will learn PHP number with 2 decimals. Rounding numbers to a specific decimal place is a common use in programming.

We will give you more method to converting float to 2 decimal places. So, let us see in detail an example.

  • Using number_function() function
  • Using round() function
  • Using sprintf() function
PHP format number with 2 decimals example
Using number_format() Function

The number_format() function is used to formatting numbers as string with grouped. You can use the number_format() function to format a float to  a specified numbers of decimal places.

Example
<?php

$origanalFloatValue = 3.23456;

$formattedFloatValue = number_format($origanalFloatValue, 2);

echo "OriginalValue: $origanalFloatValue";
echo "Formatted Value: $formattedFloatValue";

?>

In this example, the number_format function is used with $originalFloatValue and the number of decimal places you want 2 in this example. The result is stored in $formattedFloatValue, and you can then use it as needed.

Output:
OriginalValue: 3.23456
Formatted Value: 3.23
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.

Syntax:
round(float $number, int $precision)
Example
<?php

$floatNumber = 4.252525;
$formatted = round($floatNumber, 2);
echo $rounded;

?>

4.252525 is rounded to 4.25.

Using sprintf() function

The sprintf() function is used to formatting strings, and it can also be for rounding numbers to a specific number of decimal places.

Example:
<?php

$flotNumber = 4.252525;
$formatted = sprintf("%.2f", $flotNumber);
echo $formatted;
?>

Explanation:

  • “%.2f” specifiea a floating-point numbers (f) with 2 decimal places.

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *