Reputation: 1321
I'm trying to implement a for loop that increments by 0.1. I have one that seems to work just fine for an increment of 0.5. Although this may be a 'false positive' since the one for 0.1 gives me some strange values for i?
function thisisi() {
var x = 1;
for (var i = (x+0.1); i < 2; i += 0.1) {
console.log('i', i);
}
};
Seems to yield:
i 1.1
i 1.2000000000000002
i 1.3000000000000003
i 1.4000000000000004
i 1.5000000000000004
i 1.6000000000000005
i 1.7000000000000006
i 1.8000000000000007
i 1.9000000000000008
Instead of what I need which is 1.1, 1.2, 1.3 etc.
Can someone please point out the root of my idiocy?
Upvotes: 2
Views: 3645
Reputation: 437
Try this :
function thisisi(){
var x = 1;
for (var i = x; i < 2; i += 0.1) {
var str = Math.floor( i * 1000 ) / 1000;
console.log(str);
}
};
thisisi();
Upvotes: 1
Reputation: 2960
Just as "one third" (1/3) cannot be expressed precisely in decimal (0.333...) then one-tenth (0.1) cannot be expressed precisely in binary (it's 0.0001100110011...).
Upvotes: 2
Reputation: 38112
You can use .toFixed() to limit the number of digits appear after the decimal point:
function thisisi() {
var x = 1;
for (var i = (x+0.1); i < 2; i += 0.1) {
console.log('i', i.toFixed(1));
}
};
Upvotes: 4