Created
March 14, 2019 15:07
-
-
Save bmadigan/d4ace57dc8bb4ea762e1b13800eefade to your computer and use it in GitHub Desktop.
Currency conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** @test */ | |
public function it_converts_currency_to_cents_if_dollar_sign() | |
{ | |
$this->assertEquals(6500, convertCurrencyToCents('$65')); | |
$this->assertEquals(6600, convertCurrencyToCents('$66.00')); | |
$this->assertEquals(6750, convertCurrencyToCents('$67.50')); | |
$this->assertEquals(2500, convertCurrencyToCents('25.00')); | |
$this->assertEquals(3300, convertCurrencyToCents('33')); | |
$this->assertEquals(1150, convertCurrencyToCents('$11.5')); | |
$this->assertEquals(0, convertCurrencyToCents('$0.00')); | |
$this->assertEquals(0, convertCurrencyToCents('0')); | |
$this->assertEquals(0, convertCurrencyToCents('0.00')); | |
} | |
/** | |
* Convert money from UI into cents | |
* | |
* @param $amount | |
* @return int|string | |
*/ | |
function convertCurrencyToCents($amount) | |
{ | |
$amount = str_replace('$', '', $amount); | |
$amount = str_replace(',', '', $amount); | |
$amount = str_replace(' ', '', $amount); | |
// If theres a . we need to account for that. | |
$newAmount = explode('.', $amount); | |
// No decimal places given | |
if (sizeof($newAmount) == 1) { | |
return $newAmount[0] . '00'; | |
} else { | |
// Sometimes, a user could put a single decimal place | |
// Eg. $11.5 | |
if(strlen($newAmount[1]) === 1) { | |
return $newAmount[0] . $newAmount[1] . '0'; | |
} | |
} | |
return intval($newAmount[0] . $newAmount[1]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment