Removing currency symbol from formatCurrency

别说谁变了你拦得住时间么 提交于 2020-07-30 08:09:19

问题


I'm trying to format revenue totals as grabbed from a db, and using php's NumberFormatter class, with the formatCurrency method.

However, I do not want to print out the actual € / Euro symbol with this. I just want the plain number, with comma's and decimal points.

Example; 1234.56 should be formatted as 1,234.56 The current output is giving €1,234.56.

Code I'm using:

$array['total_revenue'] = $this
    ->db
    ->query($sql)
    ->row_array()['SUM( booking_total )'];

$formatter = new NumberFormatter('en_GB',  NumberFormatter::CURRENCY);

echo $formatter->formatCurrency($array['total_revenue'], 'EUR') . PHP_EOL;

Would anyone have any ideas on how I can fix this up to remove the euro symbol?


回答1:


A simple regex is a quick fix for your problem. Try;

$actual = $formatter->formatCurrency($array['total_revenue'], 'EUR') . PHP_EOL;
$output = preg_replace( '/[^0-9,"."]/', '', $actual );
echo $output;

Hope this helps




回答2:


You should use setSymbol() function:

$formatter = new NumberFormatter('en_GB',  NumberFormatter::CURRENCY);
$formatter->setSymbol(NumberFormatter::CURRENCY_SYMBOL, '');
echo $formatter->formatCurrency($array['total_revenue'], 'EUR') . PHP_EOL;



回答3:


I came here because for some reason, $formatter->setSymbol(NumberFormatter::CURRENCY_SYMBOL, ''); was being ignored by $formatter->formatCurrency($array['total_revenue'], 'USD');

To resolve this issue, I found out a solution here. https://www.php.net/manual/en/numberformatter.setsymbol.php#124153

this could be obvious to some, but setSymbol(NumberFormatter::CURRENCY_SYMBOL, '') doesn't work for formatCurrency - it will simply be ignored...

use NumberFormatter::CURRENCY and $fmt->format(123); to get a currency value with the symbol specified as CURRENCY_SYMBOL (or INTL_CURRENCY_SYMBOL)

i.e

    $fmt = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
    $fmt->setSymbol(NumberFormatter::CURRENCY_SYMBOL, '');
    $fmt->setAttribute(NumberFormatter::FRACTION_DIGITS, 2);
    echo $fmt->format(56868993064.7985);
    //Output: 56.868.993.064,80 



回答4:


You can use the substr() method, although I'm not sure if that'd be the correct way to do it. Like shown below :

echo substr($formatter->formatCurrency($array['total_revenue'], 'EUR'), 1) . PHP_EOL;


来源:https://stackoverflow.com/questions/33944074/removing-currency-symbol-from-formatcurrency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!