0

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

6round
  • 182
  • 4
  • 18
  • You want to round down like that? – StackSlave Feb 12 '18 at 09:20
  • How to convert negative numbers to positives has been answered in this duplicate [**Convert a negative number to a positive one in JavaScript**](https://stackoverflow.com/questions/4652104/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**](https://stackoverflow.com/questions/4187146/truncate-number-to-two-decimal-places-without-rounding) – Nope Feb 12 '18 at 09:33

3 Answers3

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.
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • @gurvinder372 thank u for replay if my value in positive also it will work – 6round Feb 12 '18 at 09:19
  • Linked to several duplicates answering all this already with lots of variations, including this/similar regex, etc.. – Nope Feb 12 '18 at 09:36
3

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);
Eddie
  • 26,593
  • 6
  • 36
  • 58
2

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);
pwolaq
  • 6,343
  • 19
  • 45