I am trying to create an array that begins at 0.05 and ends at 2.5. I want the values in between the min and max to grow by increments of 0.245.
var min = 0.05;
var max = 2.5;
var increments = ((max - min) / 100);
var arr = [];
the final output should be like this:
[0.05, 0.0745, 0.99, 0.1235, 0.148 ... 2.5]
I am trying to create an array that begins at 0.05 and ends at 2.5. I want the values in between the min and max to grow by increments of 0.245.
var min = 0.05;
var max = 2.5;
var increments = ((max - min) / 100);
var arr = [];
the final output should be like this:
[0.05, 0.0745, 0.99, 0.1235, 0.148 ... 2.5]
Share
Improve this question
edited Mar 26, 2014 at 9:41
Mark Walters
12.4k6 gold badges35 silver badges48 bronze badges
asked Mar 26, 2014 at 9:39
BwyssBwyss
1,8343 gold badges28 silver badges50 bronze badges
2
- 2 I see nothing wrong with your approach so far. – Tibos Commented Mar 26, 2014 at 9:41
- How can I create a loop that will produce the final output array? – Bwyss Commented Mar 26, 2014 at 9:42
7 Answers
Reset to default 5using ES6/ES2015 spread operator you can do this way:
let min = 0.05,
max = 2.5,
items = 100,
increments = ((max - min) / items);
let result = [...Array(items + 1)].map((x, y) => min + increments * y);
if you need to round your numbers to x number of digits you can do this way:
let result = [...Array(items + 1)].map((x, y) => +(min + increments * y).toFixed(4));
Here is an example of the code
do like
var min = 0.05;
var max = 2.5;
var increments = ((max - min) / 100);
var arr = [];
for(var i=min; i<max;i=i+increments) {
arr.push(i);
}
arr.push(max);
console.log(arr);
Try this:
var min = 0.05;
var max = 2.5;
var increments = ((max - min) / 100);
var arr = [];
for (var i = min; i < max; i +=increments) {
arr.push(i);
}
arr.push(max);
The basic idea is this:
for (var val=min; val<=max; val+=increments) {
arr.push(val);
}
Keep in mind that floating point operations often have rounding errors. To fix them, you might want to round the value at each step:
var val = min;
while (val <= max) {
arr.push(val);
val += increments;
val = Math.round(val*1000)/1000; // round with 3 decimals
}
In some cases you may get wrong results due to rounding errors if you just increment number on each iteration. More correct way is:
var min = 0.05;
var max = 2.5;
var increments = (max - min) / 100;
var arr = [];
for (var i = 0; i <= 100; ++i)
arr.push(min + increments * i);
function GetArray(minValue, maxValue, step) {
var resArray = [];
if (!isNaN(minValue) || !isNaN(maxValue) || !isNaN(step)) {
for (var i = minValue; i <= maxValue; i=i+step)
{
resArray.push(i);
}
}
return resArray;
}
you can use this function
function test(){
var min = 0.05;
var max = 2.5;
var increments = (max-min)/100;
var arr = [];
for(var min=0.05;min<=max;min=min+increments){
arr.push(min);
}
alert(arr);
}