Jump to content

format number


arianhojat

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).

so
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];
else
{
$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';
Link to comment
Share on other sites

sprintf() takes fixed arguments, so you could probably do something like this:
[code]
<?php
if (ceil($num) == floor($num)) $format = "%d";
else $format = "%2f";

$newNum = sprintf($format, $num);
echo $newNum;
?>
[/code]

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.