How to make exact decimal calculations?

I need to do decimal calculations, but sometimes the result is not accurate.

0.009 + 0.001; // => 0.009999999999999998

How can I get around this?

+4
source share
1 answer

You can use the decimal package . This package allows decimal calculations without loss of precision, such as double operations.

Decimal.parse('0.2') + Decimal.parse('0.1'); // => 0.3

Decimal.parse('0.2')returns a new object Decimalthat can be processed as num(by the way, Decimalit is not num, because it numcannot be used as a superclass or implemented).

To make the code shorter, you can define a shortcut for Decimal.parse:

final d = Decimal.parse;
d('0.2') + d('0.1'); // => 0.3
+4
source

Source: https://habr.com/ru/post/1523477/


All Articles