Sponge Coder
Sponge Coder

Reputation: 71

Format number with the thousand separator in Vue

I have division calculator and its working clearly but Im not happy with calculation result.You will understand better when you see the SS below.What I want is to delete unnecessary zeros, put commas where necessary, and show a more understandable number if the result shows the number thousand. For e.g: Not 19350.00 , this should be 19,350

Result

enter image description here

What I want

enter image description here

Template

  <input
    type="text"
    class="form-control h-35"
    autocomplete="off"
    v-model="purchasePrice"
  />
  <input
    type="text"
    class="form-control h-35"
    autocomplete="off"
    v-model="salePrice"
  />

  <p>{{ marginResult }}</p>

Script

data() {
    return {
      purchasePrice: null,
      salePrice: null,
      marginPrice: null,
    };
  },
  computed: {
    marginResult() {
      const res = parseFloat(
        ((this.salePrice - this.purchasePrice) / this.salePrice) * 100
      ).toFixed(2);
      if (isNaN(res) || res == "-Infinity") {
        return "";
      }
      return res;
    },
  },

Upvotes: 1

Views: 4926

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Just use the Intl.NumberFormat utility object to format the number :

...
return new Intl.NumberFormat('en-US').format(res);

Upvotes: 3

Related Questions