rounding question

Discussion in 'PHP' started by vassili, Apr 8, 2008.

  1. #1
    for prices, i'd like any price in the data base to round up the last digit to a 0 or 5.

    so $14.41 should be $14.45 and $14.46 should be $14.50. the prices are stored as a decimal(4,2) in mysql. ciel and floor only give me the option of rounding up or down to 0, but not 5.
     
    vassili, Apr 8, 2008 IP
  2. awatson

    awatson Active Member

    Messages:
    112
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    53
    #2
    Untested, and no doubt there's a better way, but try this ($price is the value from the db, $out_price is the rounded value):

    // keep the part of the number that won't change i.e. 14.41 becomes 1440
    $out_price = (floor($price * 10;) * 10)

    // now use mod 10 to figure out the last digit.
    $tmp = $price * 100; // 14.41 becomes 1441
    if ($tmp % 10 > 0) && ($tmp % 10 <= 5) { $out_price += 5; } // 1440 becomes 1445
    else { $out_price += 10; }
    $out_price = $out_price / 100; // becomes 14.45


    I think it'll work, but it is the end of the day :)
     
    awatson, Apr 8, 2008 IP
  3. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #3
    I was thinking similarly, but loop through the number using mod 5. Then you can increment by 1 and loop again. Once the number mod 5 returns 0, you can return the value.

    Something like:

    
    
    function roundFiveHundreths($number)
    {
    	$newNumber = $number*100;
    	
    	while($newNumber % 5 != 0)
    	{
    		$newNumber++;
    	}
    	
    	return $newNumber/100;
    }
    
    $roundThisNumber = 25.41;
    $goodNumber = roundFiveHundreths($roundThisNumber); //should be 25.45
    
    
    PHP:
     
    jestep, Apr 8, 2008 IP
  4. vassili

    vassili Peon

    Messages:
    36
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    cool, thanks for the help guys. jestep's solution's working. you should've seen the hack crap i came up with ahahah...i was using string functions...which got the job done but was ugly as hell.
     
    vassili, Apr 8, 2008 IP