Jump to content


format number

  • Please log in to reply
1 reply to this topic

#1 arianhojat

  • Members
  • PipPipPip
  • Advanced Member
  • 235 posts

Posted 30 August 2006 - 03:36 PM

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';

#2 obsidian

  • Staff Alumni
  • Advanced Member
  • 3,202 posts
  • LocationSeattle, WA

Posted 30 August 2006 - 04:12 PM

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
You can't win, you can't lose, you can't break even... you can't even get out of the game.

while (count($life->getQuestions()) > 0)
{   $life->study(); } ?>
  LINKS: PHP: Manual MySQL: Manual PostgreSQL: Manual (X)HTML: Validate It! CSS: A List Apart | IE bug fixes | Zen Garden | Validate It! JavaScript: Reference Cards RegEx: Everything RegEx

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users