1

I am learning Javascript and not getting my desired output. I will be helpful if you can correct my thinking.

This is my simple code:

<script>
window.onload = myFunction ;
function myFunction(){
 var i = 0 ;
 var counter = 1 ;
 while(i < counter){
  alert(counter);
  counter = counter - 0.1 ;
 }
}
</script>

My desired output:

1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1

But real output:

1
0.9
0.8
0.7000000000000001
0.6000000000000001
0.5000000000000001
0.40000000000000013
0.30000000000000016
0.20000000000000015
0.10000000000000014
1.3877787807814457e-16
Asif Iqbal
  • 1,132
  • 1
  • 10
  • 23
  • 2
    possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) –  Apr 24 '15 at 10:23

1 Answers1

5

This is due to Floating point arithmetic operations. You can round a float by using toFixed

Update your code to

window.onload = myFunction ;
function myFunction(){
 var i = 0 ;
 var counter = 1 ;
 while(i < counter){
  alert(counter);
  counter = (counter - 0.1).toFixed(1) ;
 }
}
thomaux
  • 19,133
  • 10
  • 76
  • 103