Reputation: 5037
I figure this is easy enough but I am missing something here. Im using Stripe Connect and trying to calculate an application fee (in cents). The problem is my application fee sometimes has a decimal so it is throwing an error. I have tried using round() which gives me and ceil() but Im still getting a decimal and trailing zero in my answer so it returns an error.
$payment = bcmul($request->amount, 100); //112.00 - Convert to cents for stripe becomes 11200
$applicationFee = $payment * 0.021; //235.2 but should be just 235
print_r($applicationFee); //Should be whole number, round and ceil still provide me with decimal number IE 235.0 instead of 235
How can I make sure applicationFee is always a whole number with no decimal and rounded to nearest whole number?
Upvotes: 6
Views: 9137
Reputation: 2412
This should work! (using round()
function)
Documentation: Round()
$payment = bcmul($request->amount, 100);
$applicationFee = $payment * 0.021;
print_r(round($applicationFee));
Upvotes: 2
Reputation: 1290
Php automatically assigns a data type when you don't specifically tell it. For this to work you have to assign a data type that allows you to do the calculations you are trying to do.
Insure you dimension them with enough space for your calculations.
Then as a last step round it off to the precision that you desire and print it out.
It is highly unlikely that if you let PHP select the data type that you will get what you want. You have to carefully select for PHP what data type your variables are instantiated as.
Upvotes: 1
Reputation: 8102
You are correct as is described in the docs for ceil:
The return value of ceil() is still of type float
The method explanation also tells you that a float is returned:
float ceil ( float $value )
The return type for round()
is also shown as a float in the docs for round as below:
float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )
You could use intval() instead as below:
intval($applicationFee);
Or try casting to an int as below:
(int) $applicationFee
If you want to keep your ceil or rounding you can call these first and then cast it as below:
intval(ceil($applicationFee));
(int) ceil($applicationFee);
Upvotes: 7
Reputation: 1712
round() should do the trick
$applicationFee = round($payment * 0.021);
You could add more parameters to round and so allow some decimals sill present in the result.
You say you tried it, but I wonder how.
Note 21 is is some countries the VAT percentage (taxes). Be careful how you round those numbers, as the tax office can be strickt
question: according to the docs round() returns a float, as it can also round to 1 or more decimals. But if the 2nd parameter is omitted you should get a whole number. How does a float equal to 235.0 influence the rest of the script?
Upvotes: 1