Print Currency Number Format in PHP

Print Currency Number Format in PHP

The easiest answer is number_format().

echo "$ ".number_format($value, 2);

If you want your application to be able to work with multiple currencies and locale-aware formatting (1.000,00 for some of us Europeans for example), it becomes a bit more complex.

There is money_format() but it doesn't work on Windows and relies on setlocale(), which is rubbish in my opinion, because it requires the installation of (arbitrarily named) locale packages on server side.

If you want to seriously internationalize your application, consider using a full-blown internationalization library like Zend Framework's Zend_Locale and Zend_Currency.

How to format number to currency but don't show the symbol?

To keep it easy MultiSuperFreaks answer is the most common. The function number_format is not deprecated in any way.

If you want to use the intl extension and the NumberFormatter class, you can go like ...

$formatter = new NumberFormatter('en_GB', NumberFormatter::DECIMAL);
$formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, 2);
var_dump($formatter->format(23)); // string(5) "23.00"

Just do not use the NumberFormatter::CURRENCY type. Instead use the NumberFormatter::DECIMAL type when instanciating the NumberFormatter class and then set the attribute for minimal 2 fraction digits.

PHP money format add decimal and comma when needed

It looks like your variable is in cents, so divide it by 100

echo number_format((247936 / 100), 2, '.', ',');

Output is: 2,479.36

How do I format a number to a dollar amount in PHP

PHP also has money_format().

Here's an example:

echo money_format('$%i', 3.4); // echos '$3.40'

This function actually has tons of options, go to the documentation I linked to to see them.

Note: money_format is undefined in Windows.


UPDATE: Via the PHP manual: https://www.php.net/manual/en/function.money-format.php

WARNING: This function [money_format] has been DEPRECATED as of PHP 7.4.0. Relying on this function is highly discouraged.

Instead, look into NumberFormatter::formatCurrency.

    $number = "123.45";
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
return $formatter->formatCurrency($number, 'USD');

Get currency symbol in PHP

I achieved this using https://github.com/symfony/Intl:

Symfony\Component\Intl\Intl::getCurrencyBundle()->getCurrencySymbol('EUR')

returns

'€'.

Symfony version > 4.3

It's worth pointing out for SF4.3 and above this has been deprecated:

/**
* Returns the bundle containing currency information.
*
* @return CurrencyBundleInterface The currency resource bundle
*
* @deprecated since Symfony 4.3, to be removed in 5.0. Use {@see Currencies} instead.
*/
public static function getCurrencyBundle(): CurrencyBundleInterface
{

So, instead you can do:

use Symfony\Component\Intl\Currencies;
echo Currencies::getSymbol('AUD');

Format money number_format PHP

As added background information based on my earlier comments, in case you were having trouble separating all the inter-related concerns, and putting all the pieces together, (i don't know if you are or not); Here is some code i've used in the past solving a similar issue. I've adjusted it based on your datamodel/code and added some comments:


Personally, since keeping half the currency information in the database and the other half in code seems messy, i would add 4 columns to your monedas database table; namely (in the case of 'Ecuador' for example):

`currency_symbol`     => '$'
`decimal_separator` => '.'
`thousands_separator` => ','
`decimals` => 2

Next you want to decide what datatype you use for price values in PHP.
I'm guessing they are DECIMALs inside your database, in which case you would either use strings ('65.99') or floats (65.99) in PHP; generally string is prefered as it doesn't suffer from all the oddities that floating point numbers bring to the table.

Alternatively, you could choose to store prices in cents in your database, which would allow you to use INTEGERs (6599) in both the database and in PHP.

Lets assume you use DECIMAL in your database, and string in PHP; that way you can use the PHP BCMath functions to perform calculations reliably.
Lets also assume that all prices in your database always represent the same currency (eg: your business's local currency, lets assume its EUR).


Since prices are a complex value in your webshop-style application, you'll want a simple value class to define them.

class Price {
private $value;

public function __construct($value) {
$value = trim((string) $value);
if (!is_numeric($value) || preg_match('#^(\-)?([0-9]+)(\.[0-9]{1,2})?$#D', $value) !== 1) throw Exception('Invalid price value');
$this->value = $value;
}

public function getRawValue() {
return $this->value;
}

// When printing a price (using echo for example), print it in its converted form (defined later)
public function __toString() {
return PriceLocalization::displayLocalPrice( $this );
}
}

Next, you want an object that holds (or caches) all the information about all currencies:

class Currencies {
protected static $data = null;

protected static function pullData() {
if (is_null(static::$data)) {
$data = [];
// Pull the currency/priceconversion info from the DB
$rows = run_your_dbquery('SELECT * FROM `monera`');
foreach ($rows as $row) {
$row['id_moneda'] = (int) $row['id_moneda'];
$row['decimals'] = (int) $row['decimals'];
$data[( $row['id_moneda'] )] = $row;
}
// Cache the data incase we have to do more conversions on the current page
static::$data = $data;
}
return static::$data;
}

// Returns the entire table of currency/priceconversion info from the DB
public static function getAll() {
return static::pullData();
}

// Returns one record out of the table of currency/priceconversion info (or exception if invalid)
public static function getSpecific($id) {
$data = static::pullData();
if (array_key_exists($id, $data)) return $data[$id];
throw new Exception('Bad input');
}
}

And another object that deals with the user being able to select a currency sessionwide

class UserCurrencySelection {

// store the users choice in $_COOKIE or $_SESSION or the like (used by your currency-selection selectbox)
public static function setUserPreference($choice) {
$_SESSION['currencychoice'] = $choice;
return true;
}

// read the raw value from $_COOKIE or $_SESSION or the like (if any)
public static function getUserPreference() {
return ($_SESSION['currencychoice'] ?? null);
}

// get either the active currency's record (if any), or otherwise the default record (throw exception if neither exists)
public static function getActive() {
try {
if ($current = static::getUserPreference()) {
return Currencies::getSpecific( $current );
}
} catch (Exception $e) {}
return Currencies::getSpecific( 5 ); // <-- the id of the "default" currency (in this case 5 = EUR)
}
}

And finally, the class that actually ties everything together

class PriceLocalization {

// display a specific price adjusted to the -active- currency (with the default currency as fallback)
public static function displayLocalPrice(Price $price, array $style=[]) {
$currencyinfo = UserCurrencySelection::getActive();
return static::displayPriceAs($price, $currencyinfo, $style);
}

// display a specific price adjusted to a -specific- currency (eg: id=3 gives colombian price)
public static function displayPriceInCurrency(Price $price, $id, array $style=[]) {
$currencyinfo = Currencies::getSpecific( $id );
return static::displayPriceAs($price, $currencyinfo, $style);
}

// perform the actual conversion and formatting
protected static function displayPriceAs(Price $price, array $currencyinfo, array $style=[]) {
/* $currencyinfo = [
'id_monera' => 4,
'moneda' => 'USD',
'pais' => 'Ecuador',
'ido' => 'EC',
'cambio' => '1.13',
'impuesto' => '12',
'currency_symbol' => '$',
'decimal_separator' => '.',
'thousands_separator' => ',',
'decimals' => 2,
]; */
// the original price:
$value_src = $price->getRawValue();
// Multiply the original price with the conversion rate (`cambio`) to adjust it to this currency (giving us the pre-tax price)
$value_excl = bcmul($value_src, $currencyinfo['cambio']);
// Calculate the tax, by multiplying the adjusted price with the taxrate (`impuesto`*0.01 to adjust for it being a percentage)
$tax = bcmul($value_excl, bcmul('0.01', $currencyinfo['impuesto']));
// Add the tax to the price to get the "price including tax"
$value_incl = bcadd($value_excl, $tax);
// Decide which of the values you want to display (including or excluding tax)
$value = $value_incl;
// Decide what we want to add before/after the numeric part of the price (the html-encoded version of the currency symbol)
$label_prefix = htmlentities( $currencyinfo['currency_symbol'] . ' ');
$label_suffix = ''; // or: htmlentities( ' ' . $currencyinfo['moneda']);
// Change the number into human readable form
$label = number_format((float) $value, $currencyinfo['decimals'], $currencyinfo['decimal_separator'], $currencyinfo['thousands_separator']);
// Convert that into html
$label = htmlentities($label);
// Define some CSS classes to allow for styling
$classes_prefix = 'p';
$classes_number = 'v';
$classes_suffix = 's';
$classes_full = 'price';
// Now assemble all the pieces
$html_prefix = sprintf('<span class="%s">%s</span>', htmlentities($classes_prefix), $label_prefix);
$html_number = sprintf('<span class="%s">%s</span>', htmlentities($classes_number), $label);
$html_suffix = sprintf('<span class="%s">%s</span>', htmlentities($classes_suffix), $label_suffix);
$html_full = sprintf('<span class="%s">%s%s%s</span>', htmlentities($classes_full), $html_prefix, $html_number, $html_suffix );
// Done
return $html_full;
}
}

That's the gist of it.

You can use the $style argument that's available on each of the PriceLocalization methods to pass arbitrary information along to displayPriceAs. Based on that information you could change the way that function assembles its output. For example, you could check if $style['include_tax'] is set to true/false, and ifso adjust accordingly:

$value = (($style['include_tax'] ?? true) ? $value_incl : $value_excl);

You could style prices with:

.price   { background-color: #EEE; }
.price.p { color: red; font-weight: bold; }
.price.v { color: green; font-family: courier; }
.price.s { color: blue; font-weight: bold; }

And you could also use the $style argument above, to introduce additional classes (in specific cases).


It may also be worth setting bcscale(15); in your application, to ensure the math is done in a way that cannot result in lost partial pennies.


ps: haven't tested the code after adapting it to your code/datamodel, so it is possible i made a typo somewhere.

How to display Currency in Indian Numbering Format in PHP?

You have so many options but money_format can do the trick for you.

Example:

$amount = '100000';
setlocale(LC_MONETARY, 'en_IN');
$amount = money_format('%!i', $amount);
echo $amount;

Output:

1,00,000.00

Note:

The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows.

Pure PHP Implementation - Works on any system:

$amount = '10000034000';
$amount = moneyFormatIndia( $amount );
echo $amount;

function moneyFormatIndia($num) {
$explrestunits = "" ;
if(strlen($num)>3) {
$lastthree = substr($num, strlen($num)-3, strlen($num));
$restunits = substr($num, 0, strlen($num)-3); // extracts the last three digits
$restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.
$expunit = str_split($restunits, 2);
for($i=0; $i<sizeof($expunit); $i++) {
// creates each of the 2's group and adds a comma to the end
if($i==0) {
$explrestunits .= (int)$expunit[$i].","; // if is first value , convert into integer
} else {
$explrestunits .= $expunit[$i].",";
}
}
$thecash = $explrestunits.$lastthree;
} else {
$thecash = $num;
}
return $thecash; // writes the final format where $currency is the currency symbol.
}


Related Topics



Leave a reply



Submit