PHP maths

Busy's picture

He has: 6,151 posts

Joined: May 2001

I have
$a = $b / $c;

but it's coming back as a long decimal number, I tried
sprintf("%1.1f" and got it down to one digit after the decimal, can I get it to be a whole number only

He has: 1,016 posts

Joined: May 2002

<?php
//The 0 is how many decimals you want.
$a = number_format($b / $c, 0);
?>

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

Or, you could type cast...
$a = (int) $b / $c;

or...
$a = intval($b/$c);

To do this with sprintf, you'd use:
$a = sprintf("%d", $b/$c);

The problem with sprintf is that you've changed the datatype from a numeric (int, double, float, etc.) to a string. This isn't as big of a problem with PHP as it handles variant datatypes, but you'll have problems doing this in C/C++.

Mark Hensler
If there is no answer on Google, then there is no question.

Busy's picture

He has: 6,151 posts

Joined: May 2001

Thanks Smiling

Busy's picture

He has: 6,151 posts

Joined: May 2001

Ok everything was going fine until I added a new entry (value of 0) now it's giving me a php warning:

Warning: Division by zero in c:\phpdev\....

anyway around this warning (short of turning error warnings off Wink )
I tried all four methods mentioned above

I'm using negative, zero and postive numbers

b = whole numbers 0 ++ (no neagatives)
c = whole range (--1, 0, 1++)

a = c / b so insome cases the anser could be negative

nike_guy_man's picture

They have: 840 posts

Joined: Sep 2000

It is a mathematical law that you can't divide a number by 0, but you can divide 0 by a number. Makes sense doesn't it??
So just remove the value of 0 for the variables... what exactly is their need here?

Laughing out loud

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

<?php
$a
= ($b===0) ? 0 : (int) $b / $c;
?>

IF $b equals 0 (and is same datatype, numeric) THEN
$a = 0;
ELSE
$a = (int) $b / $c;
ENDIF

Busy's picture

He has: 6,151 posts

Joined: May 2001

Thanks guys, nike_guy_man it's a vote form value thing, but to keep the number size down in the db I'm using -2, -1, 0, 1, 2 for the vote values then the values get added or subtracted from the old value and divided by the amount of values - if that makes sense.

Mark I'll give that a go tonight after work, thanks

I did some searching last night, anyone every use 'round' or 'ceil' or 'floor'

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

Yup..

round() will round to the nearest integer, unless you specify a precission (decimal places to keep).

ceil() round up to higher integer. no args.
floor() round to lower integer. no args.

Mark Hensler
If there is no answer on Google, then there is no question.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.