Calculate value with Virgula with Vue.JS

1

Good afternoon, Vue.JS can calculate directly in the mustache {{}} but when a value comes with comma, NaN appears the result that is, if the variable is value = 2 and I make {{value - 1}} it displays 1 for good but if I make value = 2,5 and then {{value - 1}} it displays NaN

<p>{{ valor - 2 }}</p>

How could I calculate this comma value in mustaches?

    
asked by anonymous 08.11.2018 / 19:48

2 answers

3

As bfavaretto has already mentioned you can change the comma by point for JS to do automatic conversion to Number when subtraction is done.

But you could have a function to convert this string to Float and another function to format Float to String. Then just use functions to work with your data. Then how you apply in your code you choose!

In the code below I have put examples with Filters , Computed Properties and Methods .

let toFloat = str => parseFloat(str.replace(',', '.'));
let toStr = float => ("" + float).replace('.', ',');


const app = new Vue({
  el: '#app',
  data: {
    valor: "2,5",
  },
  filters: {
    sub2(value) {
      let number = toFloat(value) - 2;
      return toStr(number);
    },
  },
  computed: {
      valor_sub2() {
        let number = toFloat(this.valor) - 2;
        return toStr(number);
      },
  },
  methods: {
    method_sub2(value) {
      let number = toFloat(value) - 2;
      return toStr(number);
    }
  }
});
<script src="https://vuejs.org/js/vue.min.js"></script><divid="app">
  <input v-model="valor">
  <div>Filter: {{ valor }} - 2 = {{ valor | sub2 }}</div>
  <div>Computed: {{ valor }} - 2 = {{ valor_sub2 }}</div>
  <div>Method: {{ valor }} - 2 = {{ method_sub2(valor) }}</div>
</div>

I did not go into the merits of internationalization because it is not part of your problem, but this technique of using String.replace() is only for very restricted inputs. If you want the user to type a number and their software recognizes, you need to work on the parsing of these strings. In my example would be the toFloat() and toStr() methods. (Reading tip: Intl.NumberFormat )

    
08.11.2018 / 21:13
5

Change the comma by point:

<p>{{ valor.replace(',', '.') - 2 }}</p>

I recommend creating a computed Vue property and do the replace there, so as not to mess up your view.

Another thing, this will work for subtraction, multiplication and division, but addition will be treated as concatenation of strings, as commented above by Denis Rudnei de Souza. To add, you still need to convert to number:

+valor.replace(',', '.')

or

parseFloat(valor.replace(',', '.'))
    
08.11.2018 / 20:04