I want to create an input that displays a USD currency format with thousand-separators, but I'm struggling with limiting the price to only 3 numbers.
The goal is for this input to look different from the actual value used for calculations. Any idea what might be causing this issue?
Check out the codesandbox link provided below:
https://codesandbox.io/s/vue-template-s6jo9
Here's the code snippet:
<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>