randombits
randombits

Reputation: 48490

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 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?

Upvotes: 1

Views: 1034

Answers (1)

M. Eriksson
M. Eriksson

Reputation: 13635

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: https://3v4l.org/qAa1v

Upvotes: 2

Related Questions