Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

With the following configuration I can output an amount with a currency

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

inside a component

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

I can output:

<p>£100.20</p>

the following format can be fine on some cases but if I need to output simple amounts like: £5, £10 ect.. I cannot. I tried to configure it with no success.

like image 838
Matteo Gilardoni Avatar asked Jan 29 '23 23:01

Matteo Gilardoni


1 Answers

The vue-i18n docs indicates the number formats can include Intl.NumberFormat options, so you could set the minimumFractionDigits and maximumFractionDigits options both to zero in order to remove the decimal part from the currency.

You could define a new named format (e.g., "currencyNoCents") that uses these options:

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>
like image 143
tony19 Avatar answered Feb 05 '23 16:02

tony19