1
let minPerBar = 4;
let maxPerBar = 12;
    
    let arr = [];   
        
    for (let i = minPerBar, j = 0; i <= maxPerBar; i += 0.1, j++) {
        arr[j] = i;
    }       
    
    console.log(arr);

https://jsfiddle.net/Nata_Hamster/Lsg4nx7e/1/

I need to get an array:

[4, 4.1, 4.2, 4.3, 4.4...]

but I get actually an array

[4, 4.1, 4.199999999999999, 4.299999999999999, 4.399999999999999, 4.499999999999998, 4.599999999999998, ....]
Adam Azad
  • 11,171
  • 5
  • 29
  • 70

3 Answers3

1

You could use toFixed() with parseFloat() to get the result. toFixed() method converts a number into a string and then rounding to a specified number of decimals. At last, use parseFloat() get a floating point number.

const minPerBar = 4;
const maxPerBar = 12;

const arr = [];

for (let i = minPerBar, j = 0; i <= maxPerBar; i += 0.1, j += 1) {
  arr[j] = parseFloat(i.toFixed(1));
}

console.log(arr);
mr hr
  • 3,162
  • 2
  • 9
  • 19
1

Use toFixed() to convert to string and then use + to convert back to number.

const minPerBar = 4;
const maxPerBar = 12;

const arr = [];
let value = minPerBar;
while (value <= maxPerBar) {
  arr.push(+value.toFixed(1));
  value = value + 0.1;
}

console.log(arr);
michael
  • 4,053
  • 2
  • 12
  • 31
0

Use toFixed();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

let minPerBar = 4;
let maxPerBar = 12;
    
    let arr = [];   
        
    for (let i = minPerBar, j = 0; i <= maxPerBar; i += 0.1, j++) {
        arr[j] = i.toFixed(1);
    }       
    
    console.log(arr);
Lundstromski
  • 1,197
  • 2
  • 8
  • 17