简体   繁体   中英

VueJS - add thousands separator to input

I'm trying to create an input which will look like a USD currency with thousand-separators but I can't write price longer than 3 numbers.

I just want this input to be displayed differently than an actual value which I'll use to calculate something.

Do you know where is the problem?

Here is a codesandbox link:

https://codesandbox.io/s/vue-template-s6jo9

This is the code:

<template>
  <div id="app">
    <img width="25%" src="./assets/logo.png">
    <input v-model="fValue">
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld";

export default {
  name: "App",
  components: {
    HelloWorld
  },
  data() {
    return {
      value: ""
    };
  },
  computed: {
    fValue: {
      // getter
      get: function() {
        if (this.value !== "") {
          return this.formatUSD(this.value);
        }
      },
      // setter
      set: function(newValue) {
        this.value = this.parseUSD(newValue);
      }
    }
  },
  methods: {
    formatUSD(num) {
      return (
        "$" +
        Number(num)
          .toFixed(2)
          .replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
      );
    },
    parseUSD(text) {
      return Number(text.replace("$", "").replace(/,/g, ""));
    }
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

.toFixed(2) makes the format of the number has 2 decimals. But the problem is it puts the cursor to the last position. that's why it seems only has 3 digits of number allowed there. You can see the actual number if you console.log(num) before returning the value here(gif) .

You can actually change the cursor position before the decimal then adds more numbers there. There's another way to allow decimal . (dot) as user input.

  1. Follow the Locale Format, this will use the default system numeric format.
formatUSD(num) {
    return "$" + Number(num).toLocaleString();
},
  1. to convert it to String then use regex
formatUSD(num) {
    return (
    "$" +
    Number(num)
        .toString()
        .replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
    );
},

the other option is to make your cursor to stay before the decimal if it's not by user input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM