「JavaScript」Intl.NumberFormatを使って数値を指定した通貨単位に変換する

環境
Windows 10 home 64bit
Google Chrome 105.0.5195.127

構文
Intl.NumberFormat('locale’, {
style: 'currency’,
currency: '通貨単位’ });
Intl.NumberFormat関数を使用して数値を指定した通貨単位に変換します。
Intl.NumberFormat オブジェクトは、言語に依存した数値書式を可能にするオブジェクトのコンストラクターです。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const nn = 123456.789;
const fmt =new Intl.NumberFormat('de-DE', {
style: 'currency',
currency: 'EUR' });
console.log("ユーロ: "+fmt.format(nn));
const fmt2 = new Intl.NumberFormat('ja-JP', {
style: 'currency',
currency: 'JPY' });
console.log("円: "+fmt2.format(nn));
const fmt3 = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD' });
console.log("ドル: "+fmt3.format(nn));
const nn = 123456.789; const fmt =new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }); console.log("ユーロ: "+fmt.format(nn)); const fmt2 = new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }); console.log("円: "+fmt2.format(nn)); const fmt3 = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); console.log("ドル: "+fmt3.format(nn));
const nn = 123456.789;

const fmt =new Intl.NumberFormat('de-DE', {
  style: 'currency', 
  currency: 'EUR' });
console.log("ユーロ: "+fmt.format(nn));

const fmt2 = new Intl.NumberFormat('ja-JP', {
  style: 'currency', 
  currency: 'JPY' });
console.log("円: "+fmt2.format(nn));

const fmt3 = new Intl.NumberFormat('en-US', {    
     style: 'currency',
     currency: 'USD' });

console.log("ドル: "+fmt3.format(nn));

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
> "ユーロ: 123.456,79 €"
> "円: ¥123,457"
> "ドル: $123,456.79"
> "ユーロ: 123.456,79 €" > "円: ¥123,457" > "ドル: $123,456.79"
> "ユーロ: 123.456,79 €"
> "円: ¥123,457"
> "ドル: $123,456.79"

 

JavaScript

Posted by arkgame