PHP - String Format Number Precision

Introduction

When displaying floating-point numbers with the f or F type specifier, you can use a precision specifier to indicate how many decimal places to round the number to.

To add a precision specifier, insert a period (.), followed by the number of decimal places to use, before the type specifier:

Demo

<?php

printf("%f \n ", 123.4567);      // Displays "123.456700" (default precision)
printf("%.2f \n ", 123.4567);  // Displays "123.46"
printf("%.0f \n ", 123.4567);  // Displays "123"
printf("%.10f \n ", 123.4567); // Displays "123.4567000000"
?>/*from  w  w w . ja v a  2s .com*/

Result

You can use a padding specifier with a precision specifier.

Then the entire number is padded to the required length including the digits after the decimal point, as well as the decimal point itself:

Demo

<?php

printf("%.2f \n ", 123.4567);    // Displays "123.46"
printf("%012.2f \n ", 123.4567); // Displays "000000123.46"
printf("%12.4f \n ", 123.4567);  // Displays "    123.4567"
echo "";//from  ww w . j  a v  a 2s.  c o  m
?>

Result

If you use a precision specifier when formatting a string, printf() truncates the string to that many characters:

Demo

<?php

printf("%.8s\n", "Hello, world!");    // Displays "Hello, w"
?>//w  ww.  jav  a  2  s  .  c  o  m

Result

Related Topic