Attempting to format a number using a computed property and .toLocaleString() fails to execute

I am facing an issue with the formatting of a number displayed in a <p></p> element. The number is coming from a range input element that is bound to an amount data property using v-model. Even though I have a computed property to format the number, it doesn't appear correctly.

What I want to see
12,000
What I am seeing
12000

Check out this demo

new Vue({
      el: "#app",
      data: {
        amount: 0
      },
      computed: {
        formattedAmount(){
          return this.amount.toLocaleString()
        }
      }
    })
body {
      background: #20262E;
      padding: 20px;
      font-family: Helvetica;
    }

    #app {
      background: #fff;
      border-radius: 4px;
      padding: 20px;
      transition: all 0.2s;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

    <div id="app">
      <h2>Range Formatter</h2>
      <p>{{formattedAmount}}</p>
      <input type="range" id="range" v-model="amount" min="0" max="1000000">
    </div>

Answer №1

It seems that you're currently using toLocaleString on a string instead of a number, which is why the formatting isn't being applied as expected. To fix this, make sure to include the number modifier in your v-model.

v-model.number="amount"

Vue by default treats all values from <input> elements as strings, even when they should be numbers. By adding the number modifier, Vue will convert the string into a number before updating the bound property.

new Vue({
  el: "#app",
  data: {
    amount: 0
  },
  computed: {
    formattedAmount() {
      return this.amount.toLocaleString()
    }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <h2>Range Formatter</h2>
  <p>{{formattedAmount}}</p>
  <input type="range" id="range" v-model.number="amount" min="0" max="1000000">
</div>

Answer №2

One issue to address is that the value returned by this.amount is a string. To work with it as a number, you'll need to convert it first like this:

formattedAmount() {
   return Number(this.amount).toLocaleString();
}

new Vue({
  el: "#app",
  data: {
    amount: 0
  },
  computed: {
    formattedAmount() {
      return Number(this.amount).toLocaleString()
    }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <h2>Range Formatter</h2>
  <p>{{formattedAmount}}</p>
  <input type="range" id="range" v-model="amount" min="0" max="1000000">
</div>

Alternatively, you can utilize a .number modifier to automatically convert user input into a Number like so:

<input v-model.number="amount" type="range" id="range" min="0" max="1000000">

new Vue({
  el: "#app",
  data: {
    amount: 0
  },
  computed: {
    formattedAmount() {
      return this.amount.toLocaleString()
    }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <h2>Range Formatter</h2>
  <p>{{formattedAmount}}</p>
  <input type="range" id="range" v-model.number="amount" min="0" max="1000000">
</div>

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

Can a value be concealed within a dropdown list on a form (using PHP or JavaScript)?

Within my form, there is a drop down box listing the 50 states in the U.S. This list is generated using a PHP for loop. Users are required to select their residential state and later on, they must also choose a mailing state if it differs from their resi ...

The color of the letters from the user textbox input changes every second

My task is to create a page where the user enters text into a textbox. When the user clicks the enter button, the text appears below the textbox and each letter changes color every second. I am struggling with referencing this jQuery function $(function() ...

How can I properly integrate multer with Node and Express in this situation?

I've been working on setting up a route for uploading photos, but after making some changes, it has stopped functioning and I'm not sure how to fix it. const multer = require('multer'); // MULTER STORAGE const multerStorage = multer.di ...

A guide to increasing a loop counter in Vue

Having trouble looping through a specific group of objects in a multi-object array? Take a look at the code below: <template> <div> <h1>My Test App</h1> <button v-on:click="getHockeyData">Get Team Data< ...

The controller in Angular uses the $scope symbol _

App.controller('todoController', function ($scope) { // create a message to display in our view $scope.todos = [{ name: 'angular', done: false }]; $scope.clearTodo = function () { $scope.todos = _.filter($scope.tod ...

Guide to creating the onclick feature for a dynamic button in Meteor

<template name="actionTemplate"> {{#each action}} <button class="myButton" id={{_id}}>btn</button> {{> action}} {{/each}} </template> <template name="action"> <div class="sct" id={{_id}}> ...

Having trouble integrating a custom dialog with DirtyForms plugin

I have successfully implemented DirtyForms, a plugin that triggers a confirmation dialog when a user tries to navigate away from a page. The base functionality of the plugin is working as intended. Now, I am trying to integrate jQuery UI's Dialog for ...

Is Axios phasing out support for simultaneous requests?

According to the current axios documentation, there is a section that is not very well formatted: Concurrency (Deprecated) It is advised to use Promise.all instead of the functions below. These are helper functions for managing concurrent requests. axio ...

The pencil-drawn pixel on the canvas is positioned off-center

Currently, I am using p5.js to draw pixels on canvas with a pencil tool. However, I have encountered an issue where the pixel does not appear centered when the size of the pencil is set to 1 or smaller. It seems to be offset towards the left or right. Upo ...

What advantages does the Step function (AWS) offer compared to setTimeout (Javascript) for scheduling tasks?

I am currently in the process of developing an API service that allows any client to provide me with their HTTP request along with the desired time in seconds for execution. I have considered two potential approaches to achieve this: Utilizing a lambda f ...

How can I send an array of date and time values from a Vue.js component to an ASP.NET Core API?

Here is my API code snippet: [HttpGet("/GetBusinessDaysWithPublicHolidayDates/")] public int GetBusinessDays(DateTime startDate, DateTime endDate,[FromQuery] IList<DateTime> publicHolidays) { var noOfDays = _dayCalculatorService.Busines ...

Animate a div component sliding out while seamlessly introducing a new one using React

For my signin page, I've set it up so that users first enter their username and then click next to trigger a fluid slide animation which reveals the password field from the right. Although the separate components are already coded and the animation wo ...

The functionality of the delete button in Material UI Chip seems to be malfunctioning

I am working on mapping Material UI Chips, but I am facing an issue where the cross button is not showing up and I cannot click on them or use the onTouchTap event. Below is my mapping: {mapping.map(chipMap => { return ( <div> ...

Loop through each row in the Datatable and access the details or child

I need to iterate through each child row in a datatable. For example, if I have AJAX data structured like this: "data": [ { "date" : "1/17/2016", "supplier" : "supplier1", "total" : "$10", "payment" : "Cash", "product" : Array[2] ...

What causes Vue.js's store to clear upon refreshing with Node.js? Additionally, how can uploaded images be utilized within Vue.js?

Title is my question. First. Currently, I am working on developing a simple diary app using Node.js and Vue.js. I have implemented Vue-router with history mode and in the backend, I am using the "connect-history-api-fallback" module. Despite my efforts, w ...

What could be causing the issue with saving form data to local storage in React?

I am facing an issue with the code I have written to store data in local storage. Sometimes it works fine, but other times it saves empty data or erases the previous data when the Chrome window is closed and reopened. Any idea what could be causing this in ...

Guide on creating a menu that remains open continuously through mouse hovering until the user chooses an option from the menu

I have a unique scenario where I am working with two images. When the mouse hovers over each image, two corresponding menu bars appear. However, the issue is that when the mouse moves away from the images, the menu disappears. Any suggestions on how to im ...

Encountering a Laravel Vue issue while attempting to implement chart.js using the Laravel-charts package

While utilizing Laravel charts from , I encountered an error message below. I observed that the error vanishes when I remove this particular line (which is associated with rendering and placed in the layout before yielding content). However, upon doing so ...

Fixing Cross-Browser Issues with the OnScroll Function

window.onscroll = function() { if( window.XMLHttpRequest ) { var bodyId=document.getElementById('bodymain'); if (bodyId.scrollTop > 187) { //make some div's position fixed } else { //mak ...

Looking to eliminate the bullet point next to the labels on a highcharts graph?

I have implemented a Highcharts solid gauge in my project, and you can view a sample image https://i.stack.imgur.com/QQQFn.png However, I am facing an issue where unwanted grey bullets are appearing in the test environment but not locally. I have checked ...