WillyTheFish Posted February 22, 2010 Share Posted February 22, 2010 Hey guys, already posted this problem once, sorry about that, but i was a little unclear in what i wanted to do and still couldn't figure it out on my own. as you see below i have the number 215 which i want to round so that it end with $v1 or $v2, depending on what is closer to it... I want to return 4 possible outcomes in $a,$b,$c and $d... so $a = 145, $b = 195, $c = 245 and $d = 295.... as you see, all of them ending with either $v1 or $v2. I tried to write the code so that it will work with all kinds of numbers, if i change the variables $number, $v1 and $v2, but failed so far... This also needs to work for $number = 4.6, $v1 = 0.5 and $v2 = 0.9 if you get what i mean. $v1 = 45; $v2 = 95; $number = 215; $num_len = strlen(round($number)); $v_len = strlen(round($v1)); $a = (floor($number/pow(10,$num_len-1)) + $v1/pow(10,$v_len)) * pow(10,$num_len-1); $b = (floor($number/pow(10,$num_len-1)) + $v2/pow(10,$v_len)) * pow(10,$num_len-1); $c = (ceil($number/pow(10,$num_len-1)) + $v1/pow(10,$v_len)) * pow(10,$num_len-1); $d = (ceil($number/pow(10,$num_len-1)) + $v2/pow(10,$v_len)) * pow(10,$num_len-1); please help so i can move on thanks! Link to comment https://forums.phpfreaks.com/topic/192876-rounding-numbers-to-either-x-or-y/ Share on other sites More sharing options...
jcanker Posted February 22, 2010 Share Posted February 22, 2010 Maybe I'm misunderstanding what you're trying to do, but the way I see it, you want to basically ignore any of the digits preceding the last two (or however many are in (V1 and $v2) Perhaps you could: $strlength = $number; //get the string length $testnum = substr($number,-2) //pulls the last two from the string $testround1 = $testnum - $v1; $testround2 = $v2 - $testnum; if ($testround1 < $testround2) $newnum = substr($number,0,($strlength-2)) .$testround1; else $newnum = substr($number,0,($strlength-2)) .$testround1; I'll be honest and admit that I didn't bother thinking through about decimals, but I bet you could use the string functions to search for a decimal point and alter the number sufficiently and reverse the operation later if necessary... I hope I'm not blowing smoke around with what you're trying to do...This solution seems a bit simple to me, but sometimes we get lost in the rush to find a solution and ignore the easy and obvious...then again, maybe I'm completely misunderstanding what you want to accomplish.... Link to comment https://forums.phpfreaks.com/topic/192876-rounding-numbers-to-either-x-or-y/#findComment-1015887 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.