Unformat money when parsing in PHP
You can use
NumberFormatter::parseCurrency
- Parse a currency number
Example from Manual:
$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
var_dump($formatter->parseCurrency("75,25 €", $curr));
gives: float(75.25)
Note that the intl extension is not enabled by default. Please refer to the Installation Instructions.
What a quick way to clean up a monetary string
<?php
$money = array(
'$50.45',
'USD 50.45',
'50,45',
'USD$ 50.45'
);
// remove everything except a digit "0-9", a comma ",", and a dot "."
$money = preg_replace('/[^\d,\.]/', '', $money);
// replace the comma with a dot, in the number format ",12" or ",43"
$money = preg_replace('/,(\d{2})$/', '.$1', $money);
print_r($money);
?>
Output:
Array
(
[0] => 50.45
[1] => 50.45
[2] => 50.45
[3] => 50.45
)
Unformat money when parsing in PHP
You can use
NumberFormatter::parseCurrency
- Parse a currency number
Example from Manual:
$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
var_dump($formatter->parseCurrency("75,25 €", $curr));
gives: float(75.25)
Note that the intl extension is not enabled by default. Please refer to the Installation Instructions.
Is there any solution to convert string to money amount?
I would use a regular expression, something like:
(\w*\$)\s*([0-9,.]+)\s+(thousand|million|billion|bn)?
which will capture both the currency and value. PHP:
if (preg_match('/(\w*\$)\s*([0-9,.]+)\s+(thousand|million|billion|bn)?/i', $input, $matches)) {
$currency = $matches[1];
$value = str_replace(',', $matches[2]);
$multiplier = null;
if (isset($matches[3])) {
$multiplier = $matches[3];
}
}
Explaining the regex a bit:
(\w*\$)
captures the currency / symbol
\s*
allows for any whitespace between the currency and value
([0-9,.]+)
captures the value
(thousand|million|billion|bn)?
captures million/billion, etc. and the ?
makes it optional.
Adding money strings together and getting a total
you need to remove tha '£' from each item and then convert it to a integer then you create a variable named sum and in a loop you add each element to the sum , there you are the algorithm :
int sum = 0;
for_each (item i in basket)
{
string tmp = i.get_price() ; // get_price returns "£x" string
sum += to_integer(tmp.sub_str(1,tmp.length()-1));
/* copy from the pos 1 to the end ignoring the '£'*/
}
then the sum variable contains what you want :D
how to reformat a number with commas
You can use the number_format()
function:
$str = number_format($number);
To use "." instead of ",":
$str = number_format($number, 0, ',', '.');
Decimal money format
You can use number_format like:
$n = 2.1;
echo number_format($n, 2, ','); // 2,10
If you have commas as decimal separators in your input you can convert values to float with:
$number = floatval(str_replace(',', '.', str_replace('.', '', $string_number)));
str_replace('.', '', $string_number)
is used to remove thousand separators.str_replace(',', '.', ... )
is used to replace commas with dots.
PHP replace characters , in a string number to .
The string "3,2563"
is not a number, thus - it cannot be used as such.
It can easily be converted to a float number, using PHP function str_replace and type casting.
$number = "3,2563";
$number = (float)str_replace(",", ".", $number); // returns (float) 3.2563
// Do whatever you want to do. Now $number is a float.
Using str_replace
, the ,
is replaced with a .
Note that the decimals separator can vary, depending on your PHP configuration.
Alternative to money_format() function
If you have the Intl extension, you can use
- NumberFormatter::formatCurrency — Format a currency value according to the formatter rules.
Example from Manual
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";
echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n";
$fmt = new NumberFormatter( 'ru_RU', NumberFormatter::CURRENCY );
echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";
echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n";
Output
1.234.567,89 €
1.234.567,89 RUR
1 234 567,89€
1 234 567,89р.
Also see my answer on how to parse that formatted money string back into a float:
- PHP: unformat money
Parse a number but keep negative's
In case you have the ICU extension (which is bundled in PHP 5.3) available, try this:
$formatter = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
echo $formatter->parse('-1,234.56');
Related Topics
Blocking Comment Spam Without Using Captcha
Causes of MySQL Error 2014 Cannot Execute Queries While Other Unbuffered Queries Are Active
Convert a Comma-delimited String into Array of Integers
PHP Mail() Function on Localhost
PHP: Merge Two Arrays While Keeping Keys Instead of Reindexing
MySQLi Count(*) Always Returns 1
Remove the Last Character from a String
How to Change Public Folder to Public_Html in Laravel 5
Why Is Using a MySQL Prepared Statement More Secure Than Using the Common Escape Functions
Remove Control Characters from PHP String
Utf-8 Bom Signature in PHP Files
How to Remove Array Element and Then Re-index Array
PHP: Access Array Value on the Fly
JavaScript Equivalent of PHP'S In_Array()
Why Is PHP Session_Destroy() Not Working
What Is Autoloading; How to Use Spl_Autoload, _Autoload and Spl_Autoload_Register