Jump to content


This topic is now archived and is closed to further replies.


format number

Recommended Posts

wanted to know if number_format or sprintf can be made to do this...

basically if a variable is a float then keep it a float, and round to 2 decimals.
if its not, keep it as an int (but dont include decimal point).

22.00 evaluates to 22
22.50 evaulates to 22.50
22.550 evaulates to 22.56

i guess i can do something ghetto like this, i was hoping sprintf might do soemthing fancy:
function blah($num)
$array = explode('.', $num);
$rightHandSideDecimal = $array[1];
if($rightHandSideDecimal == 0)
$newNumber = $array[0];
$rightHandSideRounded = round( ('.'.$array[1]), 2 );
$decArray = explode( '.', $rightHandSideRounded );
$newNumber = $array[0] .'.'. $decArray[1];

return $newNumber;

echo 'blah(22.0)='.  blah(22.0).'\n';
echo 'blah(22.00)='.  blah(22.00).'\n';
echo 'blah(22.50)='.  blah(22.50).'\n';
echo 'blah(22.500)='. blah(22.500).'\n';
echo 'blah(22.55)='.  blah(22.55).'\n';
echo 'blah(22.555)='. blah(22.555).'\n';
echo 'blah(22.5000)='.blah(22.5000).'\n';

Share this post

Link to post
Share on other sites
sprintf() takes fixed arguments, so you could probably do something like this:
if (ceil($num) == floor($num)) $format = "%d";
else $format = "%2f";

$newNum = sprintf($format, $num);
echo $newNum;

basically, all i'm doing is checking to see if the number has any value after the decimal with the floor() and ceil() comparison

Share this post

Link to post
Share on other sites


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.