Home > Software design >  Format number with the thousand separator in Vue
Format number with the thousand separator in Vue

Time:08-10

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"
    
    autocomplete="off"
    v-model="purchasePrice"
  />
  <input
    type="text"
    
    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;
    },
  },

CodePudding user response:

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

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