OliverJ90
OliverJ90

Reputation: 1321

Incrementing a for loop by decimal value

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

Answers (3)

user3610762
user3610762

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

TripeHound
TripeHound

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

Felix
Felix

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

};

Fiddle Demo

Upvotes: 4

Related Questions