How to take off a percentage?

Discussion in 'PHP' started by adamjblakey, Feb 26, 2008.

  1. #1
    Hi,

    I have the following values:

    49.99
    99.99
    149.99
    199.99

    People can enter a coupon code to take away e.g. 10, 20, 30%

    How would i take away one of the above percentages away from e.g. 199.99

    Cheers,
    Adam
     
    adamjblakey, Feb 26, 2008 IP
  2. shallowink

    shallowink Well-Known Member

    Messages:
    1,218
    Likes Received:
    64
    Best Answers:
    2
    Trophy Points:
    150
    #2
    More of a math question? Just subtract the % from 1 and multiply. If its 10%, 99.99 * .9 , 20%, 99.99 * .8 etc. Which is nothing more than reversing the process. Instead of saying its 10% off, you are just charging them 90% of the price.
     
    shallowink, Feb 26, 2008 IP
  3. adamjblakey

    adamjblakey Active Member

    Messages:
    1,121
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    80
    #3
    So something like this then?

    $total = 199.99;
    $maintotal = $total*(50/100);

    The only problem with this is i get back 75 but what i need back is 74.99

    Any ideas?
     
    adamjblakey, Feb 26, 2008 IP
  4. PHPGator

    PHPGator Banned

    Messages:
    4,437
    Likes Received:
    133
    Best Answers:
    0
    Trophy Points:
    260
    #4
    Is that the case for all values?

    You could do:

    $total = 199.99;
    $maintotal = $total * 0.5; // Change 0.5 to a different value based on percentage.
    $maintotal2 = round($maintotal, 2); // Rounds to the nearest cent (in case after math you have three decimal points)
    $maintotal3 = $maintotal2 - 0.01; // Lose 1 cent to round back down to 99 cents instead of a whole number.

    // echo($maintotal3); will return $99.99 in this case
     
    PHPGator, Feb 26, 2008 IP
  5. shallowink

    shallowink Well-Known Member

    Messages:
    1,218
    Likes Received:
    64
    Best Answers:
    2
    Trophy Points:
    150
    #5
    Force the numbers to floats and format the output.

    
    <?php
    (float) $price = 99.99;
    (float) $salePrice = $price * .5;
    echo $salePrice;
    echo "<br>";
    $formatted = sprintf("%01.2f", $salePrice);
    echo $formatted;
    ?>
    
    Code (markup):
    output is :
    49.995
    49.99
     
    shallowink, Feb 26, 2008 IP