Format number in Javascript for Integer and Float types

I was stuck trying to format a Number variable when creating an output filter in Vuejs.

Originally I used

filters: {
    filterNumber(val) {
        if(typeof(val) == "number") {
            return new Intl.NumberFormat().format(val);
        }
        return val;
    }
}

That will output a number like “123456” as “123 456”. But I also want it to skip decimals. Using .toFixed(0) doesn’t work as that only accept Float variables. Casting the Intl variable to Float using parseFloat() around it didn’t work either.

The solution was to use .toLocaleString() instead, like this:

filters: {
    filterNumber(val) {
        if(typeof(val) == "number") {
            return val.toLocaleString('US', {minimumFractionDigits: 0, maximumFractionDigits: 0});
        }
        return val;
    }
}

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *