1

I was writing a code to print the sequence 0.1, 0.2, 0.3, ......,1.0 in Dart. I used while loop and wrote the following code

void main() {
  var i = 0.0;
  while (i <= 1) {
    print(i);
    i += 0.1;
  }
}

now the compiler is giving me an unexpected result of my code

0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999

Can anyone tell what exactly is happening

Muaaz Umar
  • 11
  • 2
  • Relevant: [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – lepsch Sep 14 '22 at 09:44
  • Suppose you changed your increment step to `i += 1./3;`. Since 1/3 = 0.333333 is an infinitely-repeating decimal fraction, you would not be surprised if you saw a few anomalies like this. Well, it turns out that, in the binary systems that computers typically use, 1/10 is an infinitely-repeating fraction, too. In decimal it's 0.1 exactly, but in binary it's `0.00011001100110011…` . – Steve Summit Sep 14 '22 at 18:08

1 Answers1

-1

If you need to print this toStringAsPrecision can fix this If you need it to be double again try double.parse(i.toStringAsPrecision(2));

void main() {
  var i = 0.0;
  while (i <= 1) {
    print(i.toStringAsPrecision(2));
    i += 0.1;
  }
}