arianhojat Posted August 30, 2006 Share Posted August 30, 2006 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 2222.50 evaulates to 22.5022.550 evaulates to 22.56i 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 https://forums.phpfreaks.com/topic/19168-format-number/ Share on other sites More sharing options...
obsidian Posted August 30, 2006 Share Posted August 30, 2006 sprintf() takes fixed arguments, so you could probably do something like this:[code]<?phpif (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 https://forums.phpfreaks.com/topic/19168-format-number/#findComment-82947 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.