Reputation: 107
I am new to JavaScript and facing issue with rounding decimal number. I have a object with 'n' no of key value pairs. Key value pairs can be string or number or null. I want to just target number key value pair and round the number value with 2 decimal places. Eg. If i have value as 1.798
i want to round it to 1.80
. i have no idea how many key value pair will be present in my object just want to target number value and replace it.
I tried foreach but later found it works on array type
var obj = {
name: 'abc',
term1: 0,
term2: 1.798,
term3: 1.9999,
term4: 0,
term5: null,
term6: 'xyz'
};
// Expected output
var obj = {
name: 'abc',
term1: 0,
term2: 1.80,
term3: 2.00,
term4: 0,
term5: null,
term6: 'xyz'
};
Upvotes: 1
Views: 2337
Reputation: 207511
Well you can not have the trailing zeros since numbers do not have significant digits. You can make it a string and it would maintain the zeros.
var obj = {
name: 'abc',
term1: 0,
term2: 1.798,
term3: 1.9999,
term4: 0,
term5: null,
term6: 'xyz'
};
Object.entries(obj).forEach(([key, value]) => {
if(typeof value === 'number') {
// obj[key] = value.toFixed(2) // 1.9999 -> "2.00"
obj[key] = +value.toFixed(2) // 1.9999 -> 2
}
})
console.log(obj)
Upvotes: 1
Reputation: 10975
To achieve expected result use for in to llop object
var obj = {
name: 'abc',
term1: 0,
term2: 1.798,
term3: 1.9999,
term4: 0,
term5: null,
term6: 'xyz'
};
for( let key in obj){
obj[key] = !obj[key] || isNaN(obj[key])? obj[key] : obj[key].toFixed(2)
}
console.log(obj)
codepen - https://codepen.io/nagasai/pen/dybNwEW?editors=1010
Upvotes: 1
Reputation: 475
You can use Object.keys(obj)
to loop over the keys and make decisions. Here's a working solution for your problem:
var obj = {
name: 'abc', term1: 0, term2: 1.798, term3: 1.9999, term4: 0, term5: null, term6: 'xyz'
};
for(var key of Object.keys(obj)) {
if(typeof obj[key] === 'number' && obj[key] !== 0) {
obj[key] = (Math.round(obj[key] * 100)) / 100;
}
}
Fiddle to work in: https://jsfiddle.net/x4otdeca/
Upvotes: 1
Reputation: 2365
You can use typeof
to identify numbers and .toFixed(n)
to round to n places (and return as a string, otherwise trailing 0s are lost)
var obj = {
name: 'abc',
term1: 0,
term2: 1.798,
term3: 1.9999,
term4: 0,
term5: null,
term6: 'xyz',
};
for(propertyName in obj){
if(typeof obj[propertyName] === 'number'){
obj[propertyName] = obj[propertyName].toFixed(2);
}
}
console.log(obj) // Object { name: "abc", term1: "0.00", term2: "1.80", term3: "2.00", term4: "0.00", term5: null, term6: "xyz" }
Upvotes: 3