Help with PHP function that will take $bytes and $rate (per GB) and return $total
I was hoping someone might help with a function that given two parameters:
@param $bytes : total amount in bytes of data consumed @param $rate : rate per GB, example .22 (for 22 cents)
@returns Total amount owed
Rounded to nearest cent of course. Thanks in a开发者_运维百科dvance for any help.
function blah($bytes, $rate) {
return number_format($bytes / 1000000000 * $rate, 2);
}
(Alternatively, you might want to use 1073741824 as the divisor.)
What about something like this :
function calc_price($bytes, $rate) {
return ($bytes / (1024*1024*1024)) * $rate;
}
Basically :
- take the number of bytes
- convert it to gigabytes
- multiply by the price per gigabyte
You could do the multiplication beforehand, to use 1073741824
in your code -- would be a bit faster ; but would make the code harder to understand, I suppose.
For example, the following portion of code :
var_dump(calc_price(2*1024*1024*1024, 0.22));
Will give you :
float 0.44
Note : this doesn't round to anything : it's a matter of presentation, and should be done at the presentation level, not in the function that does the calculation.
See the round
and/or number_format
functions, for that.
For example, the following portion of code :
$price = calc_price(2.56*1024*1024*1024, 0.22);
echo number_format($price, 2, '.', ',');
will give you :
0.56
function cost($bytes, $rate, $precision = 2) {
return number_format(($bytes / 1073741824) * $rate, $precision);
}
This is going to entirely depend on how your company/process defines what a GB is.
I'd do it like this, probably
define( 'GIGABYTE', pow( 10, 9 ) );
// or
//define( 'GIGABYTE', pow( 1024, 3 ) );
function calcTotal( $bytes, $rate )
{
return ( $bytes / GIGABYTE ) * $rate;
}
精彩评论