fromString static method
Approximates price
to a fraction.
Please remember that this function can give unexpected results for values that cannot be represented as a
fraction with 32-bit numerator and denominator. It's safer to create a Price object using the constructor.
Implementation
static Price fromString(String price) {
List<String> two = price.split(".");
BigInt number = BigInt.parse(two[0]);
double f = 0.0;
if (two.length == 2) {
f = double.parse("0.${two[1]}");
}
BigInt maxInt = BigInt.from(Int32.MAX_VALUE.toInt());
BigInt a;
// List<List<BigInt>> fractions = List<List<BigInt>>();
List<List<BigInt>> fractions = [];
fractions.add([BigInt.zero, BigInt.one]);
fractions.add([BigInt.one, BigInt.zero]);
int i = 2;
while (true) {
if (number > maxInt) {
break;
}
a = number;
BigInt h = a * (fractions[i - 1][0]) + (fractions[i - 2][0]);
BigInt k = a * (fractions[i - 1][1]) + (fractions[i - 2][1]);
if (h > maxInt || k > maxInt) {
break;
}
fractions.add([h, k]);
if (f == 0.0) {
break;
}
double point = 1 / f;
number = BigInt.from(point);
f = point - number.toDouble();
i = i + 1;
}
BigInt n = fractions[fractions.length - 1][0];
BigInt d = fractions[fractions.length - 1][1];
return new Price(n.toInt(), d.toInt());
}