Reputation: 1503
I'm trying to format numbers in a table, through a formatter, in a way that the thousands are separated by commas, and the decimals by a dot.
I've set up the following formatter function, which can handle non-numeric values and possible, faily null-values:
this.table.formatter = (val, col) => {
const numberWithCommas = (x, decimals) => {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
if(parts[1]){
parts[1] = Number(parts[1]).toFixed(decimals);
}
return decimals > 0 ? parts.join(".") : parts[0];
}
let res;
if (col == "period" || col == "channel") {
res = isNaN(val) ? val : " ";
return res;
} else {
const decimals = this.config.data.metric["format"]["decimals"] | 0;
if (val != null) {
if (!isNaN(val)) {
res = numberWithCommas(val, decimals);
} else {
res = val;
}
return res != " " ? this.config.data.metric["format"].prefix + " " + res + " " + this.config.data.metric["format"].postfix : "";
}else{
return "";
}
}
}
For numbers without decimals (numbers in which the variable "decimals" is 0) it works perfectly and separates the numbers by a comma. But for decimals, the results are horrible and make absolutely no sense:
edit:
This is an example raw data packet for two rows, so you can see how the original data looks like. In these cases, they are float numbers with a huge number of decimals:
Do you have any idea on what's failing here? Thanks!
Upvotes: 0
Views: 74
Reputation: 1503
A mixture of all the comments/answers received, and a little read to the documentation, allowed me to find the way:
res = val.toLocaleString("en-IN", {maximumFractionDigits: decimals, minimumFractionDigits: decimals});
Using the ".toLocaleString()" method by itself, wouldn't put the thousands separator as commas, because I'm at Spain. But setting the "en-IN" locale, started putting them as separators. Then, using the options located at the documentation, I could easily set up a fixed amount of decimals.
Now it works great. Thanks to everyone!
Upvotes: 0
Reputation: 139
Bellow code worked for me
var N = 1000;
console.log(N.toLocaleString());
You can refer to the same at numObj.toLocaleString
Upvotes: 1