This is working for all types of numbers as well as for string numbers.
Start by declaring this function in the methods of your file.
__________________Function______________
truncateAndFormatNumber(num, digits) {
const multipliedNumber = num * Math.pow(10, digits);
const roundedNumber = Math.round(multipliedNumber);
const finalNumber = roundedNumber / Math.pow(10, digits);
let formattedNumber = finalNumber.toString();
const parts = formattedNumber.split(‘.’);
parts[0] = parts[0]. replace(/\B(?=(\d{3})+(?!\d))/g, ‘,’);
formattedNumber = parts.join(‘.’);
return formattedNumber;
}
_____________ What does this function do? ____________
It takes two parameters: the number and the digits that you want to round.
while the number will be added a “,” after three digts.
_________________ How do I use it? ____________
This is the correct way to use it by adding “this. ” before
and we should change the parameters as we want.
num => parameter of the number
digits => number of the digits to have after .
this.truncateAndFormatNumber(num, digits)
__________ How I used this function _____
Here in this case, I am getting from the back end the value of the total balance, which in this case is a string. I loop through them to find my value.
total_balance is the key that I want to assign the updated value.
this.records.forEach(rec=>{
const obj={
//The total balance here was 1234658.25552.
total_balance:this.truncateAndFormatNumber(rec.total_balance,2)
//The total balance here is 1,234,658.26.
}
}
-
This topic was modified 2 years, 1 month ago by
shefariza.