How to format an input field in VueJS with thousands separator

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>

Answer №1

.toFixed(2) is a method that formats the number to have 2 decimals. However, it can be tricky because it places the cursor at the end of the number, making it appear as though only 3 digits are allowed. To see the full number, you can use console.log(num) before returning the value. Check out this gif for a visual example.

If you want to change the cursor position before the decimal and add more numbers after it, or allow the user to input a decimal point (.), there are ways to do so:

  1. Follow the Locale Format, which uses the system's default numeric format:
formatUSD(num) {
    return "$" + Number(num).toLocaleString();
},
  1. Convert the number to a string and use regex to format it:
formatUSD(num) {
    return (
    "$" +
    Number(num)
        .toString()
        .replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
    );
},

Another option is to ensure that the cursor stays before the decimal if it was not placed there by user input.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Asynchronous functions within the next context

Hello there! I am trying to send the client's IP address from the frontend in a Next.js application to the backend. To retrieve the IP, I am using the following function: async function getIP() { var clientIP = await publicIp.v4(); ...

Maintaining consistent sprite text size in THree.js while zooming with an orthographic camera

When using three.js with an orthographic camera, the size of a Sprite can be magnified or reduced when zooming the mouse. To prevent the text size from changing, consider adjusting the camera settings and applying proper texture and material to the Sprite. ...

Can you explain the distinction between sockets and proxy passing in nginx compared to uwsgi?

My latest project setup involves flask, uwsgi, and nginx. The backend solely serves json data through an API, while the client side takes care of rendering. Typically, my Nginx configuration looks like this: My usual setup (with basic proxy passing): se ...

Inject external JSON data into the router

I need to incorporate dynamic routes from an external json file in my Nuxt application, which may change during runtime. More information on a similar topic can be found here. To achieve this, I have customized the default Nuxt router with my own logic. H ...

Struggling with transitioning from the Twitter search API to the status API

While using the search API to fetch tweets from a specific user, everything was working flawlessly except for the fact that it couldn't retrieve tweets when the username contained numbers. Based on a suggestion, I switched to using the status API que ...

Error: Attempting to access property 'post' of an undefined variable is not possible

Encountering an Error: TypeError: Cannot read property 'post' of undefined at postName (http://127.0.0.1:9000/scripts/controllers/main.js:28:12) at Scope.$scope.submit (http://127.0.0.1:9000/scripts/controllers/main.js:10:7) at http: ...

Am I utilizing the htmlspecialchars function properly?

My main objective is to protect the user from malicious code and prevent XSS attacks. I have implemented a series of checks to filter the user's input before storing it in the database. The user input is stored in the $post variable. $post = htmlspec ...

Can Vue Storefront Nuxt be seamlessly integrated with Algolia Search Routing in SSR for optimal performance?

Successfully integrated Algolia search with the VSF/Next branch, mastered the basics. Next up: tackling routing. While Vanilla Nuxt works smoothly with the integration, the number of workarounds is gradually increasing. To Reproduce: clone && yarn && ya ...

The functionality of Skrollr on mobile is currently not working properly due to the inability to prevent default actions

Encountering the following error on all chromium browsers while using the Skrollr library and accessing the website through mobile: "[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See < ...

The scripts do not allow the image to be resized

Struggling to resize an image while implementing a hover effect with css and javascript. The code I have so far is: HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equ ...

Communicating through Socket.io between various Node.js routes

Building a Node.js application that utilizes the Express Framework and Socket.io has presented me with a challenge. I am struggling to receive messages from the server across different express routes. Is there a method for receiving messages sent from one ...

Switching up the gameplay in Tic Tac Toe [The Odin Project]

Hello everyone, I have a question to ask and it's my first time here, so please forgive me if I make any mistakes! I've been learning to code with a resource called The Odin Project. Up until now, I've been able to tackle each project with ...

The AngularJS Factory $http encounters an error when attempting to read the property 'length' of an undefined value

I am looking to implement a factory in my REST Controller that will return an array of Strings. I want to be able to reuse this function in my services.js file. Here is the HTML for an Autocomplete input field: <input type="text" ng-model="vertrag.ver ...

Elements that are added dynamically will not inherit the correct CSS styles, requiring JavaScript to style them properly

My <ul> element dynamically adds <li> elements, and I am attempting to make the first <li> wider at 63% while the others are at 60%. However, the first one is only getting a width of 60%. Any thoughts on why this might be happening? I ne ...

Creating dynamic forms with JQuery and ReactJS

I have been tasked with creating a form-builder that will be integrated into an application. My role is to focus on designing the front-end using ReactJS. The client’s requirements are very similar to the features of the "jQuery Form-Builder," so I decid ...

The disappearance of the Request Body in the NuxtJS ServerMiddleware Express API

I've been working on my ExpressJS and NuxtJS skills lately. I've been trying to receive data from an axios POST request, but for some reason, the req.body and req.params always turn up empty. Below are the configurations and code snippets that I& ...

The compilation of the module has encountered an error with the PostCSS loader. There is a SyntaxError at line 2, character 14 indicating an unknown

I am developing an Angular 8 application. Currently, I am incorporating AlertifyJs into my project. In the styles.css file of Angular, I have imported these libraries: @import '../node_modules/alertifyjs/build/alertify.min.js'; @import '. ...

Using AngularJS to dynamically modify filter choices

Seeking something similar to this example in the documentation, but with a unique input that can serve as a filter for "any", "name", or "phone" properties. The role switching is triggered by clicking an anchor tag. Check out the code snippet here: http:// ...

Vue - Display components next to sidebar

Having an issue with the vue-sidebar-menu. The sidebar is appearing over the components instead of beside them. Here is a screenshot of the problem: https://i.sstatic.net/cVgI6.jpg <template> <div id="app"> <sidebar-menu :menu="menu" ...

Utilizing jQuery to Retrieve Column and Row Headers of a Selected Cell

I am currently working on a JavaFX project that includes a WebView. The HTML code is being generated using a StringBuilder. My goal is to retrieve the column and row headers of the selected cell. This information is necessary for my Java code. You can ...