Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment number by 0.01 in javascript using a loop?

Problem

I was trying to build out a list of heights in the console by meteres starting from 1.20m and ending up at 2.50m.

I used this code:

var heights = []; for ( var i=1.20, l=2.5; i<l; i+=0.01 ){      heights.push(i);  }  heights = heights.join('\n'); 

If I console.log( heights ) I get:

1.2 1.21 1.22 1.23 ... 

But then at 1.37 I start getting:

1.37 1.3800000000000001 1.3900000000000001 1.4000000000000001 1.4100000000000001 1.4200000000000002 1.4300000000000002 

Questions

  • What's going on?
  • How do I fix it?

Demo

var heights = []; for ( var i=1.20, l=2.5; i<l; i+=0.01 ){      heights.push(i);  }  var heights = heights.join('\n');  document.querySelector('#output').innerText = heights;
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>JS Bin</title> </head> <body>   <div id="output"></div> </body> </html>
like image 914
hitautodestruct Avatar asked Oct 10 '13 08:10

hitautodestruct


People also ask

How do you increment a loop?

A for loop doesn't increment anything. Your code used in the for statement does. It's entirely up to you how/if/where/when you want to modify i or any other variable for that matter.

How do you increment a number in JavaScript?

JavaScript has an even more succinct syntax to increment a number by 1. The increment operator ( ++ ) increments its operand by 1 ; that is, it adds 1 to the existing value. There's a corresponding decrement operator ( -- ) that decrements a variable's value by 1 . That is, it subtracts 1 from the value.

How do you round decimals in JavaScript?

The Math. round() method rounds a number to the nearest integer. 2.49 will be rounded down (2), and 2.5 will be rounded up (3).

How do you write decimals in JavaScript?

JavaScript Number toFixed() The toFixed() method converts a number to a string. The toFixed() method rounds the string to a specified number of decimals.


1 Answers

You are doing this fine. The problem is with the inaccuracy of floating point numbers.

Why are floating point numbers so inaccurate?

If you wish to display this number then use:

heights[i].toFixed(2); 

Note that toFixed() returns a string and you will have to convert back to a float (parseFloat()) if you want to perform more numerical operations.

like image 124
George Reith Avatar answered Sep 21 '22 07:09

George Reith