My question is similar to this one but a little different.
I'd like to round at most 2 decimal places, but only if it has decimal places.
Input:
10 1.7777777 9.1 Output:
10 1.78 9.10 How can I do this in JavaScript?
My question is similar to this one but a little different.
I'd like to round at most 2 decimal places, but only if it has decimal places.
Input:
10 1.7777777 9.1 Output:
10 1.78 9.10 How can I do this in JavaScript?
var numbers = [10,1.7777777,9.1] for ( var i = 0; i < numbers.length; i++ ) { if ( (String(numbers[i])).match(/\./g) === null ) { // Check for decimal place using regex console.log(numbers[i]) } else { console.log(numbers[i].toFixed(2)); }} OR
var numbers = [10,1.7777777,9.1] for ( var i = 0; i < numbers.length; i++ ) { console.log(numbers[i] % 1 ? parseFloat(numbers[i]).toFixed(2) : numbers[i]); } // If number is whole
myNum % 1 ? parseFloat(myNum).toFixed(2) : myNum