PHP: How to format a float to fixed width/length

Updated: January 9, 2024 By: Guest Contributor Post a comment

Overview

Control over the presentation of floating-point numbers in PHP is essential for producing readable and user-friendly outputs. This comprehensive guide walks through various methods to format floats to a fixed width and precision with plenty of examples.

Introduction to String Formatting

Before diving into floating-point specifics, understand that PHP offers several ways to control the formatting of strings, which is the foundation of controlling float representations. The sprintf() function is particularly powerful, allowing formatted strings to be returned based on specified patterns.

The basics of using sprintf() start with a format string that includes placeholders for variable substitution. Placeholders for floats typically involve the f character for floating-point numbers and the d character for integers, within the context of a wider placeholder syntax that can determine the width and precision of the output.

Basic Float Formatting

Let’s start with a simple example.

$number = 123.456;
$formatted = sprintf("%8.2f", $number);
echo $formatted; // Outputs '  123.45'

This code will print out the float with a fixed width of 8 characters and a precision of 2 decimal places. The number is right-justified within this width. Should the number require fewer than 8 characters, the remaining space is filled with whitespaces.

Zero-Filling Floats

Sometimes, you may want the extra space to be filled with zeroes instead of whitespaces.

$number = 123.456;
$formatted = sprintf("%08.2f", $number);
echo $formatted; // Outputs '00123.45'

By placing a zero directly after the percent sign in the format string, you instruct PHP to use zeros to fill the additional width.

Left-Justifying Floats

To left-justify the number within the given width, use the ‘-‘ flag in the format string.

$number = 123.456;
$formatted = sprintf("%-8.2f", $number);
echo $formatted; // Outputs '123.45  '

Notice how the spaces are now after the number.

Handling Signage

You may also want to always show the sign of the number (positive or negative).

$number = 123.456;
$formatted = sprintf("%+8.2f", $number);
echo $formatted; // Outputs ' +123.45'

The ‘+’ flag before the width puts a plus sign for positive numbers and a minus for negative numbers.

Dynamic Precision and Width

Precision and width don’t have to be hardcoded. They can be dynamic by passing them as additional arguments.

$number = 123.456;
$width = 10;
$precision = 3;
$formatted = sprintf("%*.*f", $width, $precision, $number);
echo $formatted; // Outputs '   123.456'

In the format string, the asterisks are placeholders for width and precision values passed as arguments.

Currency Formatting

For monetary values, you might need to format a float as currency.

setlocale(LC_MONETARY, 'en_US.UTF-8');
$number = 123.456;
$formatted = money_format("%i", $number);
echo $formatted; // Might output '$123.46'

Note: The money_format() function is deprecated as of PHP 7.4.0. As of PHP 8.0.0, it has been removed in favor of NumberFormatter, which is built into the intl extension.

Advanced Locale-Aware Formatting

With the NumberFormatter class, you can handle complex formatting that respects locale-specific rules for a range of numbers.

$number = 1234.567;
$formatter = new NumberFormatter('de_DE', NumberFormatter::DECIMAL);
$formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, 2);
$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo $formatter->format($number); // Outputs '1.234,57'

This is particularly useful for applications that need to support internationalization.

Conclusion

This tutorial covered how to format floating-point numbers in PHP to fixed lengths and fixed precisions, from basic examples to more advanced locale-aware methods. With these tools, you should be well-prepared to handle number formatting to match your application’s specific needs with clear, precise presentation.