0

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.

7
  • Should be array_nums = [3,000, 2,000, 1,000] Commented Oct 5, 2017 at 18:13
  • I noticed when I parse it 3,000 becomes 3. It should be 3000. Same happens for the others too. Commented Oct 5, 2017 at 18:15
  • Your array has six numbers not 3, the , is a separator in JavaScript, not a decimal point, use 3.000 instead. Commented Oct 5, 2017 at 18:20
  • The problem is these elements in the array are coming from an XML file with the values 3,000 2,000 and 1,000. Thus it really is three numbers. The XML file was already formatted that way. Commented Oct 5, 2017 at 18:22
  • @user8723305 - you'll need to manipulate the data coming in from the xml in order to end up with the intended array of integers. As is, this array is actually 6 elements ... [3, 0, 2, 0, 1, 0] which would output to ["3,000", "0", "2,000", "0", "1,000", "0"] Commented Oct 5, 2017 at 18:37

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Why are you using jQuery?
I just copied the question code snippet. It's not needed actually.
Is it possible to include the commas so that it reads 1,000,000 or 2,000,000 for example?
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.