admin管理员组

文章数量:1355607

How to change all negative values to positive values in an array using javascript, for example:

const arry = [-2.5699, -1.4589, -3.2447, -6.9789 ,-9.213568];

My result should be [2.56, 1.45, 3.24, 6.97, 9.21]

How is it possible in javascript?

I tried with Math.abs but I am getting NaN

How to change all negative values to positive values in an array using javascript, for example:

const arry = [-2.5699, -1.4589, -3.2447, -6.9789 ,-9.213568];

My result should be [2.56, 1.45, 3.24, 6.97, 9.21]

How is it possible in javascript?

I tried with Math.abs but I am getting NaN

Share Improve this question edited Feb 12, 2018 at 10:35 6round asked Feb 12, 2018 at 9:15 6round6round 1825 silver badges18 bronze badges 2
  • You want to round down like that? – StackSlave Commented Feb 12, 2018 at 9:20
  • How to convert negative numbers to positives has been answered in this duplicate Convert a negative number to a positive one in JavaScript and How to truncate decimals without rounding has been answered in this duplicate Truncate number to two decimal places without rounding – Nope Commented Feb 12, 2018 at 9:33
Add a ment  | 

3 Answers 3

Reset to default 5

I tried with Math.abs but I getting NAN

Use map

var arry = [-2.5699, -1.4589, -3.2447, -6.9789 ,-9.213568];
arry = arry.map( s => Math.abs(s));

Demo

var arry = [-2.5699, -1.4589, -3.2447, -6.9789, -9.213568];
arry = arry.map(s => Math.abs(s));
console.log(arry);

Edit

In short (as @pwolaq suggested)

arry = arry.map(Math.abs)

Edit 2

Missed the rounding off part

var fnRound = (s) => +String(s).match(/\d+\.?\d{0,2}/)[0];

var arry = [-2.5699, -1.4589, -3.2447, -6.9789, -9.213568];
arry = arry.map(Math.abs).map( fnRound ); 

Demo

var fnRound = (s) => +String(s).match(/\d+\.?\d{0,2}/)[0];

var arry = [-2.5699, -1.4589, -3.2447, -6.9789, -9.213568];
arry = arry.map(Math.abs).map( fnRound ); 
console.log(arry);

Regex Explanation /\d+\.?\d{0,2}/

  • \d+ to match digits before decimal
  • .? to match a decimal 0 or 1 times.
  • \d{0,2} to match 2 digits after decimal.

You can use Math.abs to return the absolute value of a number.

const arry = [-2.5699, -1.4589, -3.2447, -6.9789, -9.213568];

const arry2 = arry.map( v => Math.floor( Math.abs(v) * 100) / 100 );

console.log(arry2);

If you really want to truncate your numbers, not round them, then following code will work:

var arry = [-2.5699, -1.4589, -3.2447, -6.9789 ,-9.213568];
arry = arry.map(value => Math.floor(Math.abs(value) * 100)/100);

本文标签: change all minus values to positive values in array using javascriptStack Overflow