Page 1 of 1

php 20%

Posted: Wed Apr 25, 2012 12:58 pm
by YoussefSiblini
Hi Guys,
I want to take 20% off my product price which is 006385 it has to be like this as HSBC accept them this way, this means that the product price is $63.85.
I tried this:

Code: Select all

	
$TwePercent = 006385 * 0.2;   // get the 20% amount       
$PriceWithTwenPercOff = 006385 - $TwePercent;  // the price after we take the 20% off
the above $TwePercent outout is:1277
$PriceWithTwenPercOff is outputing: 6374.8

I think the $PriceWithTwenPercOff should be 005108 ($51.08).

So over all, how to get the 80% of the 006385, how can I achieve this keeping the format this way like 51.85 will read 005185?


Joe

Re: php 20%

Posted: Wed Apr 25, 2012 1:26 pm
by Celauran
The leading zeroes are going to cause problems. I recommend storing the prices normally and only formatting them before sending them to HSBC.

Code: Select all

<?php

$price = 63.85;
$discount = 0.20;
$discounted = number_format($price * (1 - $discount), 2);
$discounted = str_pad(str_replace('.', '', $discounted), 6, '0', STR_PAD_LEFT);
echo $discounted;

Re: php 20%

Posted: Wed Apr 25, 2012 1:34 pm
by YoussefSiblini
Thank you this did it,
Can you please tell me how these 2 lines works, so I know how to use it for future use, I am still newbie with php :)

$discounted = number_format($price * (1 - $discount), 2);
$discounted = str_pad(str_replace('.', '', $discounted), 6, '0', STR_PAD_LEFT);

Re: php 20%

Posted: Wed Apr 25, 2012 1:45 pm
by Celauran
YoussefSiblini wrote:Thank you this did it,
Can you please tell me how these 2 lines works, so I know how to use it for future use, I am still newbie with php :)

$discounted = number_format($price * (1 - $discount), 2);
$discounted = str_pad(str_replace('.', '', $discounted), 6, '0', STR_PAD_LEFT);

Code: Select all

$discounted = number_format($price * (1 - $discount), 2);
number_format()
Since we're dealing with currency, we know it must be only 2 decimal places. Your example happened to work out nicely, but what if the discount had been 25%? This just rounds to two decimal places.

Code: Select all

$discounted = str_pad(str_replace('.', '', $discounted), 6, '0', STR_PAD_LEFT);
Here we're removing the decimal since HSBC doesn't want it, then we pad the string with 0 on the left until it's 6 characters long.
str_pad()
str_replace()

Re: php 20%

Posted: Wed Apr 25, 2012 1:53 pm
by YoussefSiblini
Thank you sooooo much.
You made it so easy and nicely clear for me.