如何在 vue-i18n 中显示带小数点和不带小数点的货币

How can I display currency with decimal and without it in vue-i18n

通过以下配置,我可以输出带有货币的金额

const numberFormats = {
    "en-GB": {
        currency: {
            style: 'currency', currency: 'GBP'
        }
    },
    "en-US": {
        currency: {
            style: 'currency', currency: 'USD'
        }
    }
}

组件内部

<p>{{ $n(100.20, 'currency') }}</p>

我可以输出:

<p>£100.20</p>

以下格式在某些情况下可能没问题,但如果我需要输出简单的金额,如:5 英镑、10 英镑等。我不能。我尝试配置它但没有成功。

vue-i18n docs indicates the number formats can include Intl.NumberFormat options,因此您可以将 minimumFractionDigitsmaximumFractionDigits 选项都设置为零,以便从货币中删除小数部分。

您可以定义一个使用这些选项的新命名格式(例如,"currencyNoCents"):

const numberFormats = {
  'en-US': {
    currency: {
      style: 'currency', currency: 'USD'
    },
    currencyNoCents: {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 0, // set fraction digits to 0 to remove cents
      maximumFractionDigits: 0
    }
  },
  'en-GB': {
    currency: {
      style: 'currency', currency: 'GBP'
    },
    currencyNoCents: {
      style: 'currency',
      currency: 'GBP',
      minimumFractionDigits: 0, // set fraction digits to 0 to remove cents
      maximumFractionDigits: 0
    }
  },
}

const i18n = new VueI18n({
  locale: 'en-GB',
  numberFormats
})

new Vue({
  i18n
}).$mount('#app')
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script>

<div id="app">
  <p>{{ $n(100.20, 'currency') }}</p>
  <p>{{ $n(100.20, 'currencyNoCents') }}</p>
</div>