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?

3
  • the output is a string, i suppose? Commented Apr 19, 2017 at 8:43
  • Have you tried using the modulus operator? Or anything for that matter? (See minimal reproducible example) Commented Apr 19, 2017 at 8:45
  • Seriously? myNum % 1 ? parseFloat(myNum).toFixed(2) : myNum Commented Apr 19, 2017 at 8:49

2 Answers 2

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));

Sign up to request clarification or add additional context in comments.

Comments

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.