Maintaining number of digits after decimal points.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
klevis miho
Forum Contributor
Posts: 413
Joined: Wed Oct 29, 2008 2:59 pm
Location: Albania
Contact:

Re: Maintaining number of digits after decimal points.

Post by klevis miho »

Try number_format:

$a = '2';
$b = '2.6';
$c = '3.55';

echo number_format($a, 2, '.', '') . '<br>';
echo number_format($b, 2, '.', '') . '<br>';
echo number_format($c, 2, '.', '') . '<br>';
abhay440
Forum Newbie
Posts: 1
Joined: Tue Nov 02, 2010 3:19 pm

Re: Maintaining number of digits after decimal points.

Post by abhay440 »

number_format will only format the digits after decimal places. Use padding to prefix your number with '0'. I prefer to use printf and sprintf for formatting.

Code: Select all

$a = '2.6';
$temp = sprintf("%.2f", $a);
$result = sprintf("%05s", $temp);
echo $result;  //Outputs: 02.60
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Maintaining number of digits after decimal points.

Post by requinix »

You can actually combine those two into %05.2f.

sprintf manual page
Post Reply