最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Incrementing a for loop by decimal value - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked May 12, 2014 at 9:58 OliverJ90OliverJ90 1,3213 gold badges23 silver badges42 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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

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

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();
发布评论

评论列表(0)

  1. 暂无评论