Incrementing 0.1 in floating point number 0.0 gives unexpected result in Dart

Viewed 28

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

1 Answers

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;
  }
}
Related