简体   繁体   中英

Dividing variables in PHP rounding

I have a simple calculator script for making calculations of facebook insights.

There is a function in my script called fb_growth where I pass two arguments in: one for the current month's data ($moc) and one for the previous month's data ($mop) and I am trying to find the growth percentage (positive or negative) between the 2. Here is my function script:

//Growth Calculator Function
function fb_growth($moc, $mop) {
    if($moc>=$mop) {
        $grp = ($moc/$mop);
        $grf = ($grp - 1);
        return $grf;
    }
    else if($moc<$mop) {
        $grp = ($mop/$moc);
        $grf = (1 - $grp);
        return $grf;
    }
}

The values I enter in are coming from a form that the user fills out. In this particular case, the numbers passed in are fb_growth($fbfi1, $fbfi2); where $fbfi1 equals the string '1719223' and $fbfi2 equals the string '1859867'. In this case, $moc is less than $mop, so 1719223 gets divided by 1859867, which should return 1.08180672315, but instead it returns 1, which then gets subtracted by 1 to get 0. What I want to end up with is '-.08180672315', which would be my growth percentage, but I cannot get it to give me this outcome. If I echo ("1859867"/ "1719223"); then I get 1.08180672315, but when the strings are held in the variables and I echo ("$fbfi2" / "$fbfi1"); then I get 1.

I tried settype() to a double and an int for $grf and for both $fbfi1 & 2 and same result. If I set $grf as a global and echo gettype(), it will give me the double or the int, but I still get the same value: 0. Is there something I can adjust in my php settings for this, or is there something wrong with my setup? I can't find any documentation. Help is MUCH appreciated, thank you!!

PHP does automatic casting, see the type juggling manual . Integer division yields integer result (hence the 1 ).

Cast the values before doing arithmetic calculations: (float) $var

And the problem was... comma's in the entry numbers!! I was inputing 123,456 instead of 123456. That's what you get when you just carelessly copy and paste sometimes..wow. Thanks for all the help though, I learned a lot about casting!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM