0
votes

I need to format a value to currency using the bootstrap-vue formatter (b-table - fields).

My current attempt:

fields: [
    { key: 'value', label: 'value(R$)', sortable: true,
        formatter: (value, key, item) => {
            return Number(item.value).toLocaleString('pt-BR', {
                style: 'decimal', currency: 'BRL'
            })
        }
    },
]

I need to somehow format these values ​​that I get from my backend (axios).

Can help-me?

3
What is it that's not working with your current code?Hiws

3 Answers

1
votes

To format a number to a currency using toLocaleString you need to use the style: 'currency' option.

You can read more about toLocaleString here. If you scroll down to the examples, and continue down to the using options section, you will see a couple example of the style: 'currency' option. Which is where i found the information.

For the different options you can also refer to the Intl.NumberFormat parameters section.

Note that this will not do any currency conversions.

See below snippet.

new Vue({
  el: '#app',
  data() {
    return {
      items: [
        { value: 123.45 },
        { value: 23 },
        { value: 12.6 }
      ],
      fields: [
          { key: 'value', label: 'value(R$)', sortable: true,
              formatter: (value, key, item) => value.toLocaleString('pt-BR', {style: 'currency', currency: 'BRL'})
          },
      ]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/bootstrap-vue.min.js"></script>

<link href="https://unpkg.com/[email protected]/dist/bootstrap-vue.css" rel="stylesheet" />
<link href="https://unpkg.com/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />

<div id="app">
  <b-table :items="items" :fields="fields"></b-table>
</div>
0
votes

I was also able to do it this way:

{ key: 'value', label: 'value(R$)', sortable: true,
    formatter: (value, key, item) => {
        return Number(item.value/100).toLocaleString('pt-BR', {minimumFractionDigits: 2, style: 'decimal', currency: 'BRL'})
    }
},
0
votes

toLocaleString didn't work for me, this a possible solution:

      formatter: (value, key, item) => {
        let formatter = new Intl.NumberFormat("es-ES", {
          style: "currency",
          currency: "EUR",
          minimumFractionDigits: 2
        });
        return formatter.format(value);
      }

Thanks.