PHP offers the built-in number_format function for formatting numbers. You can easily specify the number of decimal places to keep two decimal places.
$number = 10.5678;
$formatted_number = number_format($number, 2);
echo $formatted_number;
The code above outputs 10.57, successfully keeping two decimal places.
The sprintf function is commonly used for formatting strings and also supports number formatting. By setting a format template, you can specify the decimal places.
$number = 10.5678;
$formatted_number = sprintf("%.2f", $number);
echo $formatted_number;
This outputs 10.57, keeping two decimal places.
The round function performs rounding on floating-point numbers. Combined with multiplication and division, it can keep two decimal places.
$number = 10.5678;
$formatted_number = round($number * 100) / 100;
echo $formatted_number;
This method also outputs 10.57.
The intval function converts a number to an integer. By scaling the number up and then down, you can truncate to keep specific decimal places.
$number = 10.5678;
$multiplier = 100; // multiplier
$formatted_number = intval($number * $multiplier) / $multiplier;
echo $formatted_number;
The output is also 10.57.
The bcadd function supports arbitrary precision arithmetic, suitable for scenarios requiring high accuracy.
$number = "10.5678";
$precision = 2; // decimal places
$formatted_number = bcadd($number, 0, $precision);
echo $formatted_number;
The output is 10.57, with precision effectively controlled.
There are many ways to keep two decimal places in PHP, commonly including number_format, sprintf, round, intval, and bcadd functions. Developers can choose the method based on their specific needs to balance precision and code simplicity. For calculations sensitive to precision, such as financial calculations, bcadd is recommended to ensure accuracy.