Search
 
SCRIPT & CODE EXAMPLE
 

PHP

php sprintf


There are already some comments on using sprintf to force leading leading zeros but the examples only include integers. I needed leading zeros on floating point numbers and was surprised that it didn't work as expected.

Example:
<?php
sprintf('%02d', 1);
?>

This will result in 01. However, trying the same for a float with precision doesn't work:

<?php
sprintf('%02.2f', 1);
?>

Yields 1.00. 

This threw me a little off. To get the desired result, one needs to add the precision (2) and the length of the decimal seperator "." (1). So the correct pattern would be

<?php
sprintf('%05.2f', 1);
?>

Output: 01.00

Please see http://stackoverflow.com/a/28739819/413531 for a more detailed explanation.
Comment

php sprintf

$formatted = sprintf("%01.2f", $money);
Comment

PREVIOUS NEXT
Code Example
Php :: laravel @disabled in laravel-9 
Php :: factory laravel laravel 8 tinker 
Php :: test post request laravel 
Php :: excel date format in php 
Php :: enqueue css 
Php :: check if checkbox is not checked laravel 8 
Php :: update image in database using php 
Php :: php error check 
Php :: php string search in array 
Php :: reset id auto increment after deleting a table row in phpmyadmin 
Php :: sanitize file name 
Php :: custom autoload without composer 
Php :: how to install laravel 
Php :: laravel password require one letter and one number 
Php :: convertir datetime a string en php 
Php :: php cookies 
Php :: laravel except method 
Php :: how to call php function from ajax 
Php :: php exec get pid 
Php :: wordpress post autosave time 
Php :: codeigniter 3 or where in 
Php :: author page url from the current post 
Php :: laravel collection times 
Php :: php date list 
Php :: how to create 404 page in php website 
Php :: jquery greater than or equal to 
Php :: symfony messenger 
Php :: laravel store file 
Php :: script inside php 
Php :: Hide Categories - Woocommerce Product Page 
ADD CONTENT
Topic
Content
Source link
Name
1+3 =