Convert Cents to Dollars and Return a Floating Point Value
I Have a Php Application Where I Am Looking to Convert Cents to Dollars. the Return Value Should Be of Type Float, with Two Decimal Precision. Here's What My...
I have a PHP application where I am looking to convert cents to dollars. The return value should be of type float, with two decimal precision. Here's what my current function looks like:
function centsToDollars(int $cents)
{
return number_format(($cents/100), 2, '.', ',');
}
number_format return value is of type string. It passes this PHPUnit test:
/** @test */
public function it_should_convert_cents_to_dollars()
{
$centAmount = 10532399;
$dollarAmount = centsToDollars($centAmount);
$this->assertEquals("105,323.99", $dollarAmount);
}
The test I would like it to pass would be the following:
/** @test */
public function it_should_convert_cents_to_dollars()
{
$centAmount = 10532399;
$dollarAmount = centsToDollars($centAmount);
$this->assertEquals(105323.99, $dollarAmount);
}
Is there a cast I can use to my function or a different function all together I can use to make the second test pass?
1 Answer
If you set the thousand separator to an empty string and cast the response as float, it should work.
return (float)number_format(($cents/100), 2, '.', '');
With the thousand separator, the result won't be a real numeric value and you won't be able to cast it properly into one.
Demo: