Number formatting/padding before and after the decimal
Before i came up with this solution, i had some trouble formatting and padding decimal numbers, specifically when i want to do it before and after the decimal mark. To top it all, i wanted the result signed (with a plus sign(+) or minus sign(-) depending on the value of the variable)
Example:
I want this “-4.3″ into this “-04.3″
Or this “6″ into this “+06.0″
PHP has a lot of number formatting options, from number_format, to sprontf and printf. Well, just search the php docs and you will see what i mean.
The thing is that, as always, i wanted to do it in as less code as possible so, to do what i mentioned above, and after a bit of testing, i came up with this:
$value = -14.6;
printf('%1$s%2$02d.%3$01s', ($value <0 ) ? '-' : '+',floor(abs($value)),(abs($value)-floor(abs($value)))*10);
Although pretty simple, i think its still a bit contrived and dirty. But it works.
A bit of background:
the first part of the printf means:
%1 will contain the first parameter (the value after the first comma), with $s as the format (in sprintf, ’s’ means string, so it will just output the result of the first parameter, no formatting)
%2 has $02d as format so it will show a pad of two digits of an integer treated number showed as decimal
%3 has $01s as format - like i mentioned for %1, shows a string with a pad of one digit
Since i want to keep these posts simple, to serve as reference and jump to other reference sites, i will just leave some links:
PHP docs for sprintf (it has all the formatting…formats):
Just ask if you need any more feedback or help.
No Comments
RSS feed for comments on this post. TrackBack URL
Sorry, the comment form is closed at this time.