Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
705 views
in Technique[技术] by (71.8m points)

formatting - Get currency symbol in PHP

Let's start with simple piece of code to format money with NumberFormatter:

$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
echo $formatter->formatCurrency(123456789, 'JPY');

This prints: ¥123,456,789.

This is ok if you want to format money.

But what I want to do is to get currency symbol (e.g. ¥) for given currency ISO 4217 code (e.g. JPY).

My first guess was to try using:

$formatter->getSymbol(NumberFormatter::CURRENCY_SYMBOL);

But that gives currency symbol for locale given in constructor (en_US), $ in my case.

Is there a way to get currency symbol by currency ISO 4217 code in PHP?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all, there is no international global currency symbol table, that anyone on the planet could read and understand.

In each region/country the currency symbols will differ, that`s why you must determine them based on who is reading, using the browser / user locale.

The correct way is as you guessed, using NumberFormatter::CURRENCY_SYMBOL, but you first have to set the appropriate locale like en-US@currency=JPY:

$locale='en-US'; //browser or user locale
$currency='JPY';
$fmt = new NumberFormatter( $locale."@currency=$currency", NumberFormatter::CURRENCY );
$symbol = $fmt->getSymbol(NumberFormatter::CURRENCY_SYMBOL);
header("Content-Type: text/html; charset=UTF-8;");
echo $symbol;

This way the symbol will be understandable by the user.

For example, $symbol will be:

  • Canadian dollar (CAD) : CA$ in USA, CAD in Romania , $CA in Iran
  • Iran Rial (IRR): IRR in USA, while in Iran will be ?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...