Current Location: Home> Latest Articles> Four Practical Methods to Format Numbers to 6 Decimal Places in PHP

Four Practical Methods to Format Numbers to 6 Decimal Places in PHP

gitbox 2025-08-08

How to Format Numbers to 6 Decimal Places in PHP

In PHP development, it’s common to format numbers to a fixed number of decimal places. This article introduces several methods to convert numbers to 6 decimal places for flexible application.

Format Numbers Using number_format Function

The number_format function can format a number to a specified number of decimal places. By setting the decimal parameter to 6, you can achieve 6 decimal places.

$number = 3.14159;
$formattedNumber = number_format($number, 6);
echo $formattedNumber;

The output will be: "3.141590".

Format Numbers Using sprintf Function

The sprintf function formats a number into a string based on a specified format. Using the format string "%.6f" allows formatting to 6 decimal places.

$number = 3.14159;
$formattedNumber = sprintf("%.6f", $number);
echo $formattedNumber;

The output will be: "3.141590".

Use round Function for Rounding

The round function rounds a number to the specified number of decimal places. By passing 6 as the second argument, you round the number to 6 decimal places.

$number = 3.14159;
$roundedNumber = round($number, 6);
echo $roundedNumber;

The output will be: "3.141590".

Use bcdiv Function for High Precision Decimal Handling

The bcdiv function performs high-precision division and allows specifying the number of decimal places in the result. Setting the divisor to 1 and decimal places to 6 converts the number to 6 decimal places.

$number = 3.14159;
$decimalPlaces = 6;
$dividedNumber = bcdiv($number, 1, $decimalPlaces);
echo $dividedNumber;

The output will be: "3.141590".

All these four methods can effectively format numbers to 6 decimal places. Developers can choose the suitable function based on their specific needs.

Summary

This article shared four PHP functions — number_format, sprintf, round, and bcdiv — to achieve number formatting with 6 decimal places. Whether for display or precise calculations, these methods cover various scenarios.