PHP formula needed to calculate a simple format
I am trying to take an amount and convert it to a units type format...
For example:
( note: don't worry about the dollar sign )
Total is $400
I need to display it as 4 * 100
Another Example
Total is $450
I need to display it as 4 * 100 | 50 * 1
So another wor开发者_如何学JAVAds there are only 100 and 1 units.
I was thinking for 3 hours already and nothing seems to come to mind...Perhaps someone out there has done something similar and already know the answer?
Hoping I am not doing your homework. Try this:
$num = 450;
$ones = $num % 100;
$hundreds = floor($num / 100);
echo "$hundreds * 100 | $ones * 1";
Here's a simple implementation
$amount = 450;
$hundreds = floor($amount / 100);
$ones = $amount % 100;
$string = array();
if( $hundreds )
$string[] = "$hundreds * 100";
if( $ones )
$string[] = "$ones * 1";
echo implode(' | ', $string);
Check out the modulus (%) operator
Here's a simple solution which will only show the units present, you can get rid of the array/join stuff if you always need to show both units:
$total = 400;
$out = array();
$hundreds = floor($total / 100);
if ($hundreds) {
$out[] = $hundreds . ' * 100';
}
$ones = $total % 100;
if ($ones) {
$out[] = $ones . ' * 1';
}
echo join(' | ', $out);
Use the modulus operator to break down the number (this kind of thing is good to learn how to do because you'll need it for many other units conversion tasks like seconds -> minutes & seconds conversion):
$value=450;
$ones = $value % 100;
$hundreds = floor($value / 100);
echo "$hundreds * 100 | $ones * 1\n";
精彩评论