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
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>
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.
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.
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).
JavaScript Number toFixed() The toFixed() method converts a number to a string. The toFixed() method rounds the string to a specified number of decimals.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With