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
- 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
3 Answers
Reset to default 5I 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
or1
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
版权声明:本文标题:change all minus values to positive values in array using javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744027774a2578352.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论