Jump to content

number format


Recommended Posts

Hey I cant seem to think how to cut off most of the numbers after a decimal point. I want to make 0.0270721925134 look like 0.02 im sure its something simple too. I use the number format funtion sometimes but Im not sure how to get it to do that.

Link to post
Share on other sites
That function returns a string, though. PHP has a proper number function that rounds off numbers:http://uk3.php.net/round
echo round(0.0270721925134, 2); // Returns 0.02

That will actually print 0.03I don't think PHP has a function that will truncate decimal points. I use this function to round to multiples. You can use it to truncate decimal points too.
function mround($number, $multiple, $round=0) {	//This function rounds a number to the nearest multiple of $multiple	//The $round argument specifies whether to round up, down, or whichever is closer	$value = 'NaN';	if (is_numeric($number) && is_numeric($multiple)) {		switch ($round) {			case -1: //Round down				$value = floor($number/$multiple)*$multiple;				break;			case 1: //Round up				$value = ceil($number/$multiple)*$multiple;				break;			default: //Round either up or down, whichever is closer				$value = round($number/$multiple)*$multiple;				break;		}	}	return $value;}

You'd use it like this:echo mround(0.0270721925134, .01, -1);

Link to post
Share on other sites
Yeah, that's right. Though for precision it's usually better to round it than to truncate or round upwards.
True, but there are occasionally applications for rounding up or truncating.
Link to post
Share on other sites

Thanks guys, I had a feeling that I had done this once before (at school last year,) a simple round($variable, 2) did the trick. It was the ' , 2 ' that I forgot how to do.

Link to post
Share on other sites

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.   Paste as plain text instead

  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.

Loading...
×
×
  • Create New...