Search code examples
javascriptvue.jsnumber-formatting

VueJS Number Formats real time seperate by comma when Input Intl.NumberFormat


I'm a beginner and I want to display Currency sign and seperate using comma when inserting the number input at the same time. I wrote this as I understand. So far no good. Anyone knows how ? Thanks

<template>
  <div id="app">
    <input
      type="text"
      id="cost"
      v-model="cost"
      @input="dd"
      name="cost"
      class="form-control form-control-md"
      placeholder="Enter cost of construction"
    />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      cost: "",
    };
  },
  methods: {
    dd() {
      var number = this.cost;

      new Intl.NumberFormat("en-EN", {
        style: "currency",
        currency: "USD",
      }).format(number);

      return number;
    },
  },
};
</script>

Solution

  • Sorry, a little late.

    This is actually a crappy 5-min-put-together implementation of what you want to achieve. There are much better solutions out there and if you start using this, you'll soon notice its flaws.

    But it should get you starting and help you get the gist of it.

    new Vue({
      el: '#app',
      name: 'App',
      data() {
        return {
          cost: 0,
          formatLang: 'en-EN',
          formatStyle: 'currency',
          formatCurrency: 'USD'
        }
      },
      computed: {
        formatter() {
          return new Intl.NumberFormat(this.formatLang, {
            style: this.formatStyle,
            currency: this.formatCurrency
          })
        },
        formattedCost() {
          return this.formatter.format(this.cost)
        }
      }
    })
    label {
      position: relative;
    }
    
    label input {
      position: absolute;
      width: 0;
      height: 0;
      border: none;
      outline: none;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <label @click="$refs.numberInput.focus()">
        <input ref="numberInput" type="number" v-model="cost" />
        <div class="formatted">{{ formattedCost }}</div>
      </label>
    </div>