Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

calc not right: 7x1.15 = 8.049999999999999999? #63

Closed
ghost opened this issue Mar 2, 2022 · 4 comments
Closed

calc not right: 7x1.15 = 8.049999999999999999? #63

ghost opened this issue Mar 2, 2022 · 4 comments
Labels
duplicate Indicates similar issues or pull requests question Indicates that an issue or pull request needs more information

Comments

@ghost
Copy link

ghost commented Mar 2, 2022

with the math_expressions library, we type

7*1.15

the calc result was

8.0499999999999

why it not return 8.05

@fkleon
Copy link
Owner

fkleon commented Mar 2, 2022

Hi @cnmade, check out #51 and my answer which I believe describes the same issue.

@fkleon fkleon closed this as completed Mar 2, 2022
@fkleon fkleon added duplicate Indicates similar issues or pull requests question Indicates that an issue or pull request needs more information labels Mar 2, 2022
@ghost
Copy link
Author

ghost commented Mar 2, 2022

thanks, i will try

@ghost
Copy link
Author

ghost commented Mar 2, 2022

it seems getStringAsFixed can not process very high precision.


nomore@appledeMac-mini ~/tmp $ dart run main.dart
8.05000000000000
8.0499999999999989342
8.049999999999999
nomore@appledeMac-mini ~/tmp $ cat main.dart
void main() {
    double i = 7.0 * 1.15;

    print(i.toStringAsFixed(14));
    print(i.toStringAsFixed(19));
    print(i);

}

@fkleon
Copy link
Owner

fkleon commented Mar 2, 2022

@cnmade You need to select the precision based on your application's requirements. I assume in your case you'd want a low(e) precision- maybe of 3 significant digits - so that the result is rounded correctly:

void main() {
    double i = 7.0 * 1.15;
    print(i.toStringAsFixed(3)); # prints 8.05
}

Note that the original result 8.049999999999999 only has 16 digits precision, so when asking for 19 significant digits you're getting a more precise (longer) value as per Dart's implementation of 64 bit double-precision floating point numbers.

Hope that helps!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
duplicate Indicates similar issues or pull requests question Indicates that an issue or pull request needs more information
Projects
None yet
Development

No branches or pull requests

1 participant