sepehr
8/27/2013 - 9:23 AM

PHP: Money formatters

PHP: Money formatters

<?php

/**
 * Formats money.
 *
 * @param  int     $amount   Amount in pence.
 * @param  int     $dev      Devision by value.
 * @param  string  $currency Currency sign.
 * @param  mixed   $default  Default value.
 *
 * @return string
 */
function format_money($amount, $default = 'Not set', $dev = 100, $currency = '&pound; ')
{
	if (empty($amount))
	{
		return $default;
	}

	return $currency . format_price($amount, $dev);
}

// ------------------------------------------------------------------------

/**
 * Formats amount.
 *
 * @param  int $amount Amount in pence.
 * @param  int $dev    Devision by value.
 *
 * @return string
 */
function format_amount($amount, $dev = 100)
{
	if ( ! $amount OR ! is_numeric($amount))
	{
		return $amount;
	}

	// Pence to Pound
	$dev AND $amount /= $dev;

	return $amount;
}

// ------------------------------------------------------------------------

/**
 * Formats price.
 *
 * @param  int     $amount   Amount in pence.
 * @param  int     $dev      Devision by value.
 * @param  string  $currency Currency sign.
 * @param  mixed   $default  Default value.
 *
 * @return string
 */
function format_price($amount, $dev = 100, $dec_point = '.', $thousands_sep = ',')
{
	if ( ! $amount OR ! is_numeric($amount))
	{
		return $amount;
	}

	// Pence to Pound
	$dev AND $amount /= $dev;

	return number_format($amount, 2, $dec_point, $thousands_sep);
}

// ------------------------------------------------------------------------

/**
 * Preps price value for database insertion.
 * 
 * Converts pounds to pences and prepares a price string
 * for storage as an integer value.
 * 
 * @param string $price Price string to prep.
 * @param int    $rate  Multiply rate.
 * 
 * @return int
 */
function prep_price($price, $rate = FALSE)
{
	if ( ! $price OR ! is_numeric($price))
	{
		return $price;
	}

	$rate OR $rate = 100;
	$price = str_replace(',', '', $price);

	return intval($price * $rate);
}