DEV Community

Discussion on: Daily Challenge #49 - Dollars and Cents

Collapse
 
peter279k profile image
peter279k

Here is the simple solution with PHP:

function format_money(float $amount): string {
    $amounts = explode('.', (string)$amount);
    $moneyFormat = '$%d.%s';

    if (count($amounts) === 1) {
        $floating = '00';

        return sprintf($moneyFormat, $amounts[0], $floating);
    }

    if (strlen($amounts[1]) === 1) {
      $floating = $amounts[1] . '0';

      return sprintf($moneyFormat, $amounts[0], $floating);
    }

    return sprintf($moneyFormat, $amounts[0], substr($amounts[1], 0, 2));
}