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:

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy