1

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?

Community
  • 1
  • 1
SandroMarques
  • 6,070
  • 1
  • 41
  • 46

2 Answers2

2

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 
2

You could select if you need the places or not.

function round(v) {
    return v.toFixed(v % 1 && 2);
}

console.log([10, 1.7777777, 9.1].map(round));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392