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