remove fromDouble constructor from amount due to possible precision errors

This commit is contained in:
julian 2023-04-06 17:30:33 -06:00
parent ae51ce61c3
commit 16a6619746
2 changed files with 1 additions and 51 deletions

View file

@ -4,8 +4,6 @@ import 'package:decimal/decimal.dart';
import 'package:intl/number_symbols.dart';
import 'package:intl/number_symbols_data.dart';
final _ten = BigInt.from(10);
class Amount {
Amount({
required BigInt rawValue,
@ -19,12 +17,6 @@ class Amount {
fractionDigits: 0,
);
/// truncate double value to [fractionDigits] places
Amount.fromDouble(double amount, {required this.fractionDigits})
: assert(fractionDigits >= 0),
_value =
Decimal.parse(amount.toString()).shift(fractionDigits).toBigInt();
/// truncate decimal value to [fractionDigits] places
Amount.fromDecimal(Decimal amount, {required this.fractionDigits})
: assert(fractionDigits >= 0),
@ -170,15 +162,6 @@ extension DecimalAmountExt on Decimal {
}
}
extension DoubleAmountExt on double {
Amount toAmount({required int fractionDigits}) {
return Amount.fromDouble(
this,
fractionDigits: fractionDigits,
);
}
}
extension IntAmountExtension on int {
Amount toAmountAsRaw({required int fractionDigits}) {
return Amount(

View file

@ -28,31 +28,6 @@ void main() {
expect(didThrow, true);
});
test("Named fromDouble Amount Constructor tests", () {
Amount amount = Amount.fromDouble(2.0, fractionDigits: 0);
expect(amount.fractionDigits, 0);
expect(amount.raw, BigInt.two);
expect(amount.decimal, Decimal.fromInt(2));
amount = Amount.fromDouble(2.0, fractionDigits: 2);
expect(amount.fractionDigits, 2);
expect(amount.raw, BigInt.from(200));
expect(amount.decimal, Decimal.fromInt(2));
amount = Amount.fromDouble(0.0123456789, fractionDigits: 7);
expect(amount.fractionDigits, 7);
expect(amount.raw, BigInt.from(123456));
expect(amount.decimal, Decimal.parse("0.0123456"));
bool didThrow = false;
try {
amount = Amount.fromDouble(2.0, fractionDigits: -1);
} catch (_) {
didThrow = true;
}
expect(didThrow, true);
});
test("Named fromDecimal Amount Constructor tests", () {
Amount amount = Amount.fromDecimal(Decimal.fromInt(2), fractionDigits: 0);
expect(amount.fractionDigits, 0);
@ -89,10 +64,6 @@ void main() {
Amount.fromDecimal(Decimal.fromInt(2), fractionDigits: 8).toMap(),
{"raw": "200000000", "fractionDigits": 8},
);
expect(
Amount.fromDouble(2, fractionDigits: 8).toMap(),
{"raw": "200000000", "fractionDigits": 8},
);
});
test("toJsonString", () {
@ -105,10 +76,6 @@ void main() {
.toJsonString(),
'{"raw":"200000000","fractionDigits":8}',
);
expect(
Amount.fromDouble(2, fractionDigits: 8).toJsonString(),
'{"raw":"200000000","fractionDigits":8}',
);
});
test("localizedStringAsFixed", () {
@ -145,7 +112,7 @@ void main() {
expect(
Amount.fromSerializedJsonString(
'{"raw":"200000000","fractionDigits":8}'),
Amount.fromDouble(2, fractionDigits: 8),
Amount.fromDecimal(Decimal.parse("2"), fractionDigits: 8),
);
});
});