user8723305
user8723305

Reputation: 1

ParseInt elements in array to int

Suppose you have an array of the following element basically three numbers: 2,000 3,000, and 1,000

In order to say multiply each by 1,000 you would have to parse it to be set as an int:

var i = 0;
var array_nums[3,000, 2,000, 1,000];
for(i = 0; i < array_nums.length; i++){
  array_nums[i] = parseInt(array_nums[i]);
}
arraytd_dth_1[i]*1000;
//arraytd_dth_1[i].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Once parsed I would want to multiply by them by 1,000 and display them so that it has commas for every three digits. This is just a general solution I came up with for Javascript and JQuery.

Upvotes: 0

Views: 971

Answers (3)

Thusitha
Thusitha

Reputation: 3511

2,000 is not a number. It's a String.
You should first remove the commas and then parse it to a number.

var i = 0;
var array_nums = ["3,000", "2,000", "1,000"];
for (i = 0; i < array_nums.length; i++) {
  array_nums[i] = parseInt(array_nums[i].replace(new RegExp(",", 'g'), "")) * 1000;
}
console.log(array_nums);

Upvotes: 1

LowCool
LowCool

Reputation: 1411

if you are using ES6 try let newArr = array_nums.map(data => data*1000)

Upvotes: 0

jbrown
jbrown

Reputation: 3025

You can do it in a forEach and use toLocaleString() to format with commas. Straight Javascript ... no JQuery necessary.

var array_output=[];
var array_nums = [3000, 2000, 1000];

array_nums.forEach(x => {
  array_output.push((x*1000).toLocaleString());
})

Upvotes: 0

Related Questions