NewUbuntu Developer
NewUbuntu Developer

Reputation: 25

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?

Upvotes: 0

Views: 57

Answers (5)

Gowtham
Gowtham

Reputation: 1597

var a=[1, 1.241241, 5.2133213];
var b=[];
for(var i = 0; i < a.length; i++){
    c = a[i].toFixed(1);
b.push(c);

} console.log(b);

Upvotes: 0

Iakhator
Iakhator

Reputation: 159

Using loop and toFixed:

var x = 0;
var len = my_array.length;
while(x < len){ 
  my_array[x] = my_array[x].toFixed(2); 
  x++;
}

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115282

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

Upvotes: 3

Robert Wade
Robert Wade

Reputation: 5003

This will take your input and determine first if it is a float, since you don't want integers to be changed.

cropNum(1);
cropNum(1.241241);
cropNum(5.2133213);

function cropNum(n) {
  if (Number(n) === n && n % 1 !== 0) {
    return parseFloat(Math.round(n * 100) / 100).toFixed(1)
  }

  return n;
}

// returns:
// 1
// 1.2
// 5.2

Upvotes: 0

ItayB
ItayB

Reputation: 11367

for (var i=0 ; i < a.length ; i++) {
    if (parseInt(a[i]) != a[i])
        a[i] = Number(a[i].toFixed(1));
}

The snippet above (I hope this is what you were looking for) change only numbers that aren't integers - and just return their first digit..

Upvotes: 0

Related Questions