みかづきブログ・カスタム

基本的にはちょちょいのほいです。

数値に各国の通貨単位を付与する 💰

ShopifyのStoreFront APIでtotalAmountsubtotalAmountの戻り値は、amountとcurrencyCodeになっています。

shopify.dev

shopify.dev

amountとcurrencyCodeは配送先住所に依存するようで、日本を配送先にすると、

{
  amount: "4400.0"
  currencyCode: "JPY"
}

アメリカを再送先にすると、

{
  amount: "32.0"
  currencyCode: "USD"
}

という感じに変化します。

これをいい感じに価格表示に変換するためには、Intl.NumberFormatを使うと楽々で、

new Intl.NumberFormat('ja-JP, {
  style: 'currency',
  currency: currencyCode,
}).format(amount);

developer.mozilla.org

で変換できます。

new Intl.NumberFormat('ja-JP', {
  style: 'currency',
  currency: 'JPY',
}).format('4400.00'); // -> '¥4,400'
new Intl.NumberFormat('ja-JP', {
  style: 'currency',
  currency: 'USD',
}).format('32.0'); // -> '$32.00'

といった感じです。