Reputation: 22540
I am using the number format option: curCode =‘JPY’
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency:curCode}).format(number));
// expected output: "¥123,457"
How can I return:
JPY 123,457
Upvotes: 2
Views: 88
Reputation: 21672
const number = 123457;
const curCode = "JPY";
const formattingOptions = {style: 'currency', currency: curCode, currencyDisplay: 'code'};
const numberFormat = new Intl.NumberFormat('ja-JP', formattingOptions);
const regex = new RegExp(`${curCode}\\s*`, "g");
let result = numberFormat.format(number).replace(regex,`${curCode} `);
console.log(result);
The Intl.NumberFormat
options include a currencyDisplay
property for this purpose.
currencyDisplay
How to display the currency in currency formatting. Possible values are
"symbol"
to use a localized currency symbol such as€
,"code"
to use the ISO currency code,"name"
to use a localized currency name such as"dollar"
; the default is"symbol"
.
EDIT:
And if I want to add a space before the number?
You could use .replace(/JPY\s*/g,"JPY ");
to enforce one space between JPY
and the number.
\s*
will optionally match all spaces trailing JPY
, to be sure we aren't adding excess spaces for those whose output already includes a space by default.
EDIT 2:
And what would the regex look if I have an currencycode instead of JPY hardcoded?
You could replace all instances of JPY
with your variable instead. Given that you'd need the regex to include your variable, you'd have to use the regex constructor (new RegExp()
) instead.
Upvotes: 2