Mastering Number Formatting in VueJS

While working with VueJS, I encountered difficulties in formatting numbers the way I wanted. After exploring options like the builtin currency filter and vue-numeric, I realized they required modifications to achieve the desired look. Furthermore, these solutions were not suitable for displaying iterated array members.

I aimed to implement a format that could transform 12345.59 into:

12,345.59

OR

12.345,59

OR

12 345.59

This needed to work consistently across different computer/browser locales.

Answer â„–1

Get started by installing numeral.js:

npm install numeral --save  

Create a unique custom filter:

<script>
  var numeral = require("numeral");

  Vue.filter("formatNumberCustom", function (value) {
    return numeral(value).format("0,0"); // you can customize further using the documentation
  });

  export default
  {
    ...
  } 
</script>

Implement your new filter in your code:

<tr v-for="(item, key, index) in tableRows">
  <td>{{item.integerValue | formatNumberCustom}}</td>
</tr>

Answer â„–2

Using Intl.NumberFormat() in JavaScript:</p>

<pre><code>...
created: function() {
    let num = 9876543;
    console.log(new Intl.NumberFormat().format(num))
},
...

//output -> 9 876 543

Learn more about NumberFormat on MDN

Answer â„–3

There is a convenient built-in JavaScript function specifically designed for this task.

If you can confidently assume that the variable will always be a Number and not a "number String," you may use the following syntax:

{{ num.toLocaleString() }}

For added safety, consider using:

{{ Number(num).toLocaleString() }}

Reference: https://forum.vuejs.org/t/filter-numeric-with-comma/16002/2

Answer â„–4

If you're looking for a simple solution, try the following:

<template>
  <div> {{ total | toUSD }} </div>
</template>

<script>
export default {
  data () {
    return {
      total: 123456
    }
  },

  filters: {
    toUSD (value) {
      return `$${value.toLocaleString()}`
    }
  }
}
</script>

For a more complex approach, you can use this code or the one below:

Add this in main.js

import {currency} from "@/currency";
Vue.filter('currency', currency)

Then include this in currency.js

const digitsRE = /(\d{3})(?=\d)/g

export function currency (value, currency, decimals) {
  value = parseFloat(value)
  if (!isFinite(value) || (!value && value !== 0)) return ''
  currency = currency != null ? currency : '$'
  decimals = decimals != null ? decimals : 2
  var stringified = Math.abs(value).toFixed(decimals)
  var _int = decimals
    ? stringified.slice(0, -1 - decimals)
    : stringified
  var i = _int.length % 3
  var head = i > 0
    ? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
    : ''
  var _float = decimals
    ? stringified.slice(-1 - decimals)
    : ''
  var sign = value < 0 ? '-' : ''
  return sign + currency + head +
    _int.slice(i).replace(digitsRE, '$1,') +
    _float
}

Lastly, in your template:

<div v-for="item in items">
  {{item.price | currency}}
</div>

You may also find useful information in related answers here.

Answer â„–5

Vue 3 Update

In Vue 3, the use of filters has been deprecated. Instead, we can define global properties to handle such functionality:

app.config.globalProperties.$filters = {
    formatNumber(number) {
        return Intl.NumberFormat().format(number);
    }
}

To utilize this custom filter, you can do the following:

<h2>{{ $filters.formatNumber(amount) }}</h2>

Answer â„–6

Give this code a try for those using Vue.js 2

<template>
{{lowPrice | currency}}
</template>
<script>
data:(){
 return {lowPrice: 200}
}
filters:{
      currency(value) {
 return new Intl.NumberFormat("en-US",
 { style: "currency", currency: "USD" }).format(value);
 }
    }
</script>

Note: Vue.js 3 no longer supports filters, so you can implement this logic in computed properties

<template>
{{currency}}
</template>
<script>
data:(){
 return {lowPrice: 200}
}
computed:{
      currency() {
 return new Intl.NumberFormat("en-US",
 { style: "currency", currency: "USD" }).format(this.lowPrice);
 }
    }
</script>

Answer â„–7

I come from Chile and I have implemented a custom format, for instance: $50.000.000,56

install npm install numeral --save
import numeral from 'numeral'
// incorporating a locale
numeral.register('locale', 'cl', {
  delimiters: {
    thousands: '.',
    decimal: ','
  },
  abbreviations: {
    thousand: 'm',
    million: 'M',
    billion: 'B',
    trillion: 'T'
  },
  ordinal: function (number) {
    return number === 1 ? 'er' : 'ème'
  },
  currency: {
    symbol: '$'
  }
})

// changing between different locales
numeral.locale('cl')

Subsequently, include the custom format...

Vue.filter('formatNumberMoney', function (value) {
  return numeral(value).format('0,0.')
   // there are options to display other groupings/separators, refer to the documentation
})

Answer â„–8

One potential solution is to experiment with the vue-numeral-filter plugin.

Answer â„–9

To transform numbers like 12000 into 12,000, you can utilize the following Vue filter examples

  1. Implement a global filter that is accessible throughout all components

    Navigate to the file where your Vue instance is initialized, typically (main.js)

    
    Vue.filter('format_number', function (value){
      return parseInt(value).toLocaleString()
    })
    
    

    To apply this in your Vue pages,

      {{ 12000 | format_number}}
    
  2. If you prefer using it within a single Vue file, include the following code in your component options

    
    filters: {
      format_number: function (value){
       return parseInt(value).toLocaleString()
      }
    },
    
    

    To implement in your Vue pages:

      {{ 12000 | format_number}}
    

For more information on filters, check out this documentation page

Keep in mind that Filters are not compatible with Vue 3x

Answer â„–10

<template>
    <input v-model="model" type="text" pattern="\d+((\.|,)\d+)?">
</template>

<script>
export default {
  name: "InputNumber",
  emits: ['update:modelValue'],
  props: {modelValue},
  computed: {
    model: {
      get() {
        return this.modelValue ? this.modelValue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : this.modelValue
      },
      set(value) {
        this.$emit('update:modelValue', Number(value.replaceAll(',','')))
      }
    },
  }
}
</script>

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

What is the reason for needing to refresh when submitting form data in a Node application with an HTTP POST

Code Snippet - Angular .state('studentInfo.newStudent', { url : '/new/student', templateUrl: 'students/new-student.html', controller : function($state, $http){ this.saveStudent = func ...

Tips for sending an array with all its elements from jQuery to PHP

Currently, I am attempting to transfer an array from jQuery to PHP. <input type="checkbox" id="name1" name="name[]" value="name1"> Name1 <input type="checkbox" id="name2" name="name[]" value="name2"> Name2 <input type="checkbox" id="name3" ...

How can we effortlessly generate a times table using For loops and arrays?

As someone new to JavaScript, I am eager to learn. My goal is to create two "for" loops: one to save the values of the 6 times table up to 12x6 into an array called timesTable, and another to display these values in the console (e.g., 0 x 6 = 0). Thank y ...

The search functionality for the MongoDB module is not functioning properly within my Next.js application

Working on my nextjs application, I have encountered an issue with using the mongodb node module to find all documents in one of my collections. Despite successful usage of .findOne and .updateOne for other pages like login and password reset, when I use . ...

Several onclick events on a single webpage

Despite numerous attempts and hours of reading, I am still unable to figure this out. There are two different types of card elements, each with a selection of 15 different color choices. Aside from using "a", is there anything else I can try to solve this? ...

Utilize viewport activation to determine browser width

Is there a way to dynamically add the viewport-meta tag only for devices with screen widths larger than 680px? If the screen is smaller than 680px, then the responsive style file should be enabled instead. I attempted to achieve this by placing the follow ...

What is the process for assigning specific tags to specific items within an array?

As I navigate through a list of students, I am encountering an issue with my tag functionality. Currently, when a student adds a tag to their container, it is being added to every student's tags instead of just the intended student. How can I modify t ...

Exploring deeply nested directories using the ContentNavigation component in Nuxt 3 framework

Within my content folder lies a directory named planets, housing yaml files for various planets. My goal is to display these planet pages as navigation items using the content navigation component. Currently, I am only able to obtain a link to the /plane ...

Guide on retrieving HTML content from a URL and showing it in a div

I'm trying to retrieve the content of a URL and display it within a DIV element, but I'm struggling to achieve the desired result. Below is the code I'm using: index.js fetch('https://github.com/') .then(res => res.text()) ...

``How can I easily navigate to the top of the page when changing routes in React Router DOM v6?

What is the best way to scroll to the top when a route changes in react router dom v6? In the past, I used a solution from this StackOverflow post to make my page automatically scroll to the top every time a route changed with react-router-dom v5. However ...

Issue with CORS on Next.js static files leading to broken links on version 10.1.4

Currently, my Nextjs application is fetching its static files from Cloudfront. During deployment, I upload the /static folder to S3. After updating to version 9, I encountered a strange problem where some of my CSS files are triggering a CORS error: Acces ...

How to correctly bring in a Vue.js component

I'm struggling to understand the correct method for importing components across my project for use in other files. The structure of my vue js project is outlined below: . ├── node_modules ├── public │ └── favicon.svg | └─â ...

Govern Your Gateway with Expressive Logs

I'm facing some issues with the logs in my Express Gateway: Although I followed the documentation and enabled Express Gateway logs, I cannot locate any log files under my gateway root directory. Whenever I start the gateway using the command LOG_L ...

Using jQuery to manipulate text

Can I modify this code to function within "{}" instead of using the .chord tags? (Jquery) //This code transposes chords in a text based on an array var match; var chords = ['C','C#','D','D#','E',&apo ...

Mongoose and BlueBird emerge victorious from fulfilling their promise

When using mongoose and bluebird as a promise framework, I encounter an error whenever I use "save" or "remove": Warning: a promise was created in a handler but was not returned from it I have spent days trying to resolve this issue. I have tried various ...

Dynamically load npm modules in Webpack using variables for the require statement

Is there a way to dynamically require an NPM module using a variable? Below is the sample code I've been trying, everything seems to be working fine except for importing NPM modules dynamically. const firstModule = 'my-npm-module'; const s ...

What is the best way to collapse additional submenus and perform a search within a menu?

Whenever a sub-menu is activated, only the current sub-menu should be open while the others remain closed. I need the search function to be enabled on the text box and display all items containing the specified value while also changing the color of <a ...

"Utilize Vue.js to dynamically update choices in Drop Down 2 according to the selected option in Drop Down

My initial dropdown code (Drop Down 1) is as follows: <div class="col-md-3"> <select name="t_col" v-model="dbColumn" class="form-control" v-on:change="columnChange(dbColumn)"> <option value="source_country" selected>Source Co ...

Generating a download link with an expiration feature in node.js or express for both frontend and backend operations

Hello everyone, I'm a beginner here and have recently started working with node.js and express.js. I am looking to implement a download link on my website that expires after a certain time, but I've been struggling with the code for about a week ...

Order objects in a JavaScript array

Recently, I came across a list of student data fetched from an API: const Studentdata = { "StudentName1": { "active": true, "gender": "male" }, "StudentName2": { "active": false, "gender": "male" }, "S ...