1

I couldn't resolve the following quirk when doing simple addition in Dart.

void main(){
  print(5.9+0.7);
}

The output is:

6.6000000000000005

But when I use some different numbers ;

void main(){
  print(5.9+0.6);
  print(5.9+0.7);
  print(5.9+0.8);
  print(5.9+0.9);
}

The output is :

6.5
6.6000000000000005
6.7
6.800000000000001

And here is a different example :

void main(){
  print(25.90+20.70+4);
}

The output is :

50.599999999999994

What may be the reason of this strangeness.

Is there ay solution suggestion to solve this problem?

1 Answers1

0

I'd recommend you read this article: What Every Computer Scientist Should Know About Floating-Point Arithmetic

From this article, Rounding Error - Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.

lepsch
  • 8,927
  • 5
  • 24
  • 44