Flutter has become very popular recently, and almost everyone around Flutter has started to learn this new cross-platform framework. As an excellent front-end developer, I must have learned it quickly. However, WHEN it comes to floating-point calculation, I encounter the same precision rounding problem as the front-end.
Here’s an example:
0.1 + 0.2 = 0.30000000000000004 1.0-0.9 = 0.0999999999998 0.105. ToStringAsFixed (2) = 0.1 // not 0.11Copy the code
The specific reasons are not described here, readers can Google.
In the front-end field, we usually use a third-party library to calculate floating point numbers. Here, the author often uses number-precision library. The core idea of this library is to use zoom in and out method to accurately calculate the accuracy. For example, 0.1 + 0.2 can be converted to 1 + 2 = 3, and then we can reduce it by 10 times to get 0.3. Since there is no precision problem in integer calculation, this problem can be solved neatly.
In DART, we can also use this zoom in and out method to accurately calculate floating point numbers. Here, in order to facilitate the front-end developers to seamlessly enter, the author developed number_PrecisionDart version based on number-Precision API abstraction encapsulation, which has been officially released in version 1.0.0. The syntax remains exactly the same as number-Precision, lightweight and concise, and does not rely on third-party libraries.
Install and use
Go to the project’s pubspec.yaml file and add the following code:
Dependencies: number_precision: ^ 1.0.0 + 1Copy the code
methods
+ (num1, num2, [num3,... // Add, num + num2 + num3, the first and second parameters are mandatory. Minus (num1, num2, [num3,... Num1-num2-num3 NP. Times (num1, num2, [num3,... // Multiply num1 * num2 * num3 NP. Divide (num1, num2, num3... Num1 / num2 / num3 NP. Round (num, ratioCopy the code
use
import 'package:number_precision/number_precision.dart'; NP. Strip (0.09999999999999998); // = 0.1 NP. Plus (0.1, 0.2); // = 0.3, not 0.30000000000000004 NP. Plus (2.3, 2.4); // = 4.699999999999999 NP. Minus (1.0, 0.9); // = 0.1, not 0.0999999999999999998 NP. Times (3, 0.3); // = 0.9, not 0.899999999999999999 NP. Times (0.362, 100); // = 36.2, not 36.1999999999999996 NP. Divide (1.21, 1.1); // = 1.1, not 1.099999999999999999 NP. Round (0.105, 2); // = 0.11, not 0.1Copy the code
Open source is not easy, welcome PR and STAR, project address number_precision, if there is any error, feel free to comment.