So I have this little problem.
I have a form where you can enter a number, it can be in European format, with comma as decimal (,), or American with the decimal point (.).
Knowing this, how can I convert the number format from the European American format? And the American format leave it unchanged?
I tried using this formula but the result is wrong.
$american = '12.5';
$european = '12,5';
$locale = 'it_IT.utf8';
setlocale ('LC_NUMERIC', $locale);
$fmt = new NumberFormatter ($locale, NumberFormatter::DECIMAL);
$american = $ fmt->parse($american);
$european = $ fmt->parse($europen);
response
$american = 125
$european = 12.5
Where is the problem?
php ver. 5.4.10
try following code:
$american = '12.5';
$european = '12,5';
$locale = 'en_US.utf8';
$fmt = new NumberFormatter ($locale, NumberFormatter::DECIMAL);
$american = $fmt->parse($american);
$locale = 'it_IT.utf8';
$fmt = new NumberFormatter ($locale, NumberFormatter::DECIMAL);
$european = $fmt->parse($european);
Get the desired result?
Isn't better to use str_replace() instead?
Related
I'm using this piece of code to format numbers from my database so it becomes currency
$formnum = numfmt_create( 'fr_FR', NumberFormatter::CURRENCY);
$datavalue = !empty($datavalue) ?
numfmt_format_currency($formnum, intval($datavalue), 'EUR') : '';
but if $datavalue is equal to (let say) 10, I'll get 10,00 €
But obviously what I wanted is 10 €
(if you want to try it)
$formnum = numfmt_create( 'fr_FR', NumberFormatter::CURRENCY);
$datavalue = numfmt_format_currency($formnum,intval("10"), 'EUR');
echo $datavalue;
Try something like this, using the full scope of the NumberFormatter class (namely, the FRACTION_DIGITS attribute):
$fmt = new NumberFormatter('fr_FR', NumberFormatter::CURRENCY);
$fmt->setTextAttribute(NumberFormatter::CURRENCY_CODE, 'EUR');
$fmt->setAttribute(NumberFormatter::FRACTION_DIGITS, 0);
echo $fmt->formatCurrency($datavalue, 'EUR');
Docs are here: http://php.net/manual/en/numberformatter.formatcurrency.php
In PHP I know currency codes (EUR, GBP, USD...), but I do not know locale.
I need to get a currency symbol for them
GBP -> £
EUR -> €
USD -> $
Using
$obj = new \NumberFormatter( null, \NumberFormatter::CURRENCY);
echo $obj->formatCurrency( null, 'EUR');
I can get € 0.00, so the NumberFormatter library can convert currency code to currency symbol.
But how to get currency symbol only?
$obj = new \NumberFormatter( null, \NumberFormatter::CURRENCY);
$obj->setTextAttribute ( \NumberFormatter::CURRENCY_CODE, 'EUR');
echo $obj->getSymbol ( \NumberFormatter::CURRENCY_SYMBOL);
Also do not do the translation and returns $ always.
Unfortunately this isn’t as easy as it should be, but here’s how to get the currency symbol by currency code, for a locale:
function getCurrencySymbol($locale, $currency)
{
// Create a NumberFormatter
$formatter = new NumberFormatter($locale, NumberFormatter::CURRENCY);
// Prevent any extra spaces, etc. in formatted currency
$formatter->setPattern('¤');
// Prevent significant digits (e.g. cents) in formatted currency
$formatter->setAttribute(NumberFormatter::MAX_SIGNIFICANT_DIGITS, 0);
// Get the formatted price for '0'
$formattedPrice = $formatter->formatCurrency(0, $currency);
// Strip out the zero digit to get the currency symbol
$zero = $formatter->getSymbol(NumberFormatter::ZERO_DIGIT_SYMBOL);
$currencySymbol = str_replace($zero, '', $formattedPrice);
return $currencySymbol;
}
Tested with locales: ar, cs, da, de, en, en_GB, en_US, es, fr, fr_CA, he, it, ja, ko, nb, nl, ru, sk, sv, zh
Tested with currencies: AUD, BRL, CAD, CNY, EUR, GBP, HKD, ILS, INR, JPY, KRW, MXN, NZD, THB, TWD, USD, VND, XAF, XCD, XOF, XPF
Possibly not the best solution but you could always do something like ...
$obj = new \NumberFormatter( 'en_us', \NumberFormatter::CURRENCY);
$formattedValue = $obj->formatCurrency( 0, 'EUR');
$currencySymbol = trim(str_replace('0.00','',$formattedValue));
The important thing is using a locale and value where you know the expected output format (e.g. en_us and 0.00) and you can then pick the currency symbol out correctly.
Note: this might need some adjustment for certain currencies
I'm trying to convert the string 11/24/2011 # 01:15pm to a UNIX timestamp. The format is m-d-Y # h:ia
I can't seem to get strtotime to work with the string. Is there a way to reverse the data function? Is my only choice to create a new non-default php function to convert the string?
The server is running CentOS 5, Apache 2.2 and PHP 5.2.17.
Use the more modern DateTime class (so long as you're using >= 5.3).
$unix = DateTime::createFromFormat('m/d/Y # h:ia', '11/24/2011 # 01:15pm')
->getTimestamp();
CodePad.
Under PHP 5.2, you can use strptime to parse a date-time string with a specific format, then use mktime to convert the result to a timestamp.
$timeString = '11/24/2011 # 01:15pm';
$timeArray = strptime($timeString, '%m/%d/%Y # %I:%M%p');
$timestamp = mktime(
$timeArray['tm_hour'], $timeArray['tm_min'], $timeArray['tm_sec'],
$timeArray['tm_mon']+1, $timeArray['tm_mday'], $timeArray['tm_year']+1900
);
This should be abstracted as a function, possibly two:
function strptimestamp($date, $fmt) {
$timeArray = strptime($date, $fmt);
return mktime(
$timeArray['tm_hour'], $timeArray['tm_min'], $timeArray['tm_sec'],
$timeArray['tm_mon']+1, $timeArray['tm_mday'], $timeArray['tm_year']+1900
);
}
function strpmy($date) {
return strptimestamp($date, '%m/%d/%Y # %I:%M%p');
}
Support for parsing the period abbreviation appears to vary from OS to OS. If the above doesn't work on a particular OS, try "%P" instead of "%p" or pass the time string through strtoupper (or both). The following should work under any OS, though it's preferable to get strptime to handle the entirety of the parsing, as the following is less suitable as the basis for a generic strptimestamp function.
static $pm_abbrevs = array('pm' => 1, 'p.m.' => 1, 'µµ' => 1, 'µ.µ.' => 1);
$timeString = '11/24/2011 # 01:15pm';
$timeArray = strptime($timeString, '%m/%d/%Y # %I:%M');
$period = strtolower($timeArray['unparsed']);
if (isset($pm_abbrevs[$period])) {
$timeArray['tm_hour'] += 12;
}
$timestamp = mktime(
$timeArray['tm_hour'], $timeArray['tm_min'], $timeArray['tm_sec'],
$timeArray['tm_mon']+1, $timeArray['tm_mday'], $timeArray['tm_year']+1900
);
If you replace the ' # ' with a space, then strtotime should be able to understand it natively.
<?php
$x = "11/24/2011 # 01:15pm";
$x = str_replace(" # ", " ", $x);
$y = strtotime($x);
$z = date("m-d-Y # h:ia", $y);
echo "x: $x<br />\n";
echo "y: $y<br />\n";
echo "z: $z<br />\n";
?>
Output:
x: 11/24/2011 01:15pm
y: 1322140500
z: 11-24-2011 # 01:15pm
Case sensitivity may be your issue http://php.net/manual/en/datetime.formats.php.
Perhaps run $x through strtoupper() first then str_replace('#', '', $x) (notice it's replacing # with an empty string), then try strtotime(). Hope this helps.
$search = array('/',',','#');
$replace = array('-','','');
echo strtotime( str_replace($search,$replace,'16/7/2013 # 7:30AM') );
this will replace the parts of the string in the time string you are trying to convert into a format that is acceptable to strtotime. You can always add more string parts you want to replace to the arrays.
Also you dont need to have latest php for this.
Output:
1373952600
I have some price values to display in my page.
I am writing a function which takes the float price and returns the formatted currency val with currency code too..
For example, fnPrice(1001.01) should print $ 1,000.01
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.
with the intl extension in PHP 5.3+, you can use the NumberFormatter class:
$amount = '12345.67';
$formatter = new NumberFormatter('en_GB', NumberFormatter::CURRENCY);
echo 'UK: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;
$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
echo 'DE: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;
which prints :
UK: €12,345.67
DE: 12.345,67 €
sprintf() is the PHP function for all sorts of string formatting
http://php.net/manual/en/function.sprintf.php
I use this function:
function formatDollars($dollars){
return '$ '.sprintf('%0.2f', $dollars);
}
I built this little function to automatically format anything into a nice currency format.
function formatDollars($dollars)
{
return "$".number_format(sprintf('%0.2f', preg_replace("/[^0-9.]/", "", $dollars)),2);
}
Edit
It was pointed out that this does not show negative values. I broke it into two lines so it's easier to edit the formatting. Wrap it in parenthesis if it's a negative value:
function formatDollars($dollars)
{
$formatted = "$" . number_format(sprintf('%0.2f', preg_replace("/[^0-9.]/", "", $dollars)), 2);
return $dollars < 0 ? "({$formatted})" : "{$formatted}";
}
Reference Link : https://www.php.net/manual/en/function.number-format.php
$amount = 1235.56
echo number_format($amount, 2, '.', ',');
The output is : 1,235.56
If you don't need comma in output.Please remove comma inside function.
For example
$amount = 1235.56
echo number_format($amount, 2, '.', '');
The output is : 1235.56
From the docs
<?php
$number = 1234.56;
// english notation (default)
$english_format_number = number_format($number);
// 1,235
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
?>
PHP has a function called money_format for doing this. Read about this here.
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";
echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n";
output will be
1.234.567,89 €
1.234.567,89 RUR
https://www.php.net/manual/en/numberformatter.formatcurrency.php
How do you convert a number to a string showing dollars and cents?
eg:
123.45 => '$123.45'
123.456 => '$123.46'
123 => '$123.00'
.13 => '$0.13'
.1 => '$0.10'
0 => '$0.00'
If you just want something simple:
'$' . number_format($money, 2);
number_format()
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');
i tried money_format() but it didn't work for me at all. then i tried the following one. it worked perfect for me. hopefully it will work in right way for you too.. :)
you should use this one
number_format($money, 2,'.', ',')
it will show money number in terms of money format up to 2 decimal.
In PHP and C++ you can use the printf() function
printf("$%01.2f", $money);
Note that in PHP 7.4, money_format() function is deprecated. It can be replaced by the intl NumberFormatter functionality, just make sure you enable the php-intl extension. It's a small amount of effort and worth it as you get a lot of customizability.
$f = new NumberFormatter("en", NumberFormatter::CURRENCY);
$f->formatCurrency(12345, "USD"); // Outputs "$12,345.00"
The fast way that will still work for 7.4 is as mentioned by Darryl Hein:
'$' . number_format($money, 2);
In php.ini add this (if it is missing):
#windows
extension=php_intl.dll
#linux
extension=php_intl.so
Then do this:
$amount = 123.456;
// for Canadian Dollars
$currency = 'CAD';
// for Canadian English
$locale = 'en_CA';
$fmt = new \NumberFormatter( $locale, \NumberFormatter::CURRENCY );
echo $fmt->formatCurrency($amount, $currency);
/* Just Do the following, */
echo money_format("%(#10n","123.45"); //Output $ 123.45
/* If Negative Number -123.45 */
echo money_format("%(#10n","-123.45"); //Output ($ 123.45)