NewUbuntu Developer NewUbuntu Developer - 3 months ago 21
Javascript Question

javascript math with decimal numbers

I have numbers array:
[1, 1.241241, 5.2133213]

here is numbers with dot. I want to split them and stay only like this:
[1, 1.2, 5.2]

how can I make this?

Answer

Use Number#toFixed method.

var data = [1, 1.241241, 5.2133213];

// iterate and generate new array
var res = data.map(function(v) {
  // check fractional part present if present remove 
  // the remaining part using toFixed and convert back to number
  return Math.round(v) == v ? v : Number(v.toFixed(1));
})

console.log(res);