Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  192] [ 4]  / answers: 1 / hits: 26074  / 11 Years ago, thu, october 10, 2013, 12:00:00

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>




More From » math

 Answers
15

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.


[#75102] Wednesday, October 9, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mary

Total Points: 432
Total Questions: 98
Total Answers: 98

Location: Luxembourg
Member since Tue, Jan 25, 2022
2 Years ago
;