mercredi 26 juin 2019

Is there a library for Fractions and Decimal numbers in Dart?

I have been trying to learn Dart for the past while and am really liking it so far. Currently I'm hitting some issues where tests are failing because I'm comparing doubles for equality (I know this is almost always a bad idea), but I'm surprised a modern language like Dart doesn't handle this in a smarter way.

I would like to know if there are any libraries for Dart like the decimal library for Python.

Or, if that's not the case, what the best practices are for writing unit tests for functions that return a double.

I have tried two workarounds so far:

Difference less than Epsilon
bool fractionsAreEqual(double a, double b, double epsilon) {
    return abs(a - b) < epsilon;
}

Compare Fixed Strings
bool fractionsAreEqual(double a, double b, int precision) {
    return a.toStringAsFixed(precision) == b.toStringAsFixed(precision);
}

But these seem very hack-y and not ideal.

I would like a library or suggestion on how I can do something like:

double func() {
    // Some calculations that result in a double, d
    return d;
}

double expected = 33 / 100; // Or any other fraction

expect(func(), equals(expected));

Aucun commentaire:

Enregistrer un commentaire