diff --git a/cw_core/lib/parse_fixed.dart b/cw_core/lib/parse_fixed.dart index 2b8a7ec17..321320ef2 100644 --- a/cw_core/lib/parse_fixed.dart +++ b/cw_core/lib/parse_fixed.dart @@ -1,14 +1,13 @@ -BigInt parseFixed(String value, int? decimals) { - decimals ??= 0; +BigInt parseFixed(String value, int decimals) { final multiplier = getMultiplier(decimals); -// Is it negative? - final negative = (value.substring(0, 1) == "-"); + final negative = value.startsWith("-"); if (negative) value = value.substring(1); if (value == ".") throw Exception("missing value, value, $value"); -// Split it into a whole and fractional part + if (value.startsWith(".")) value = "0$value"; + final comps = value.split("."); if (comps.length > 2) { throw Exception("too many decimal points, value, $value"); @@ -17,7 +16,6 @@ BigInt parseFixed(String value, int? decimals) { var whole = comps.isNotEmpty ? comps[0] : "0"; var fraction = (comps.length == 2 ? comps[1] : "0").padRight(decimals, "0"); - // Check the fraction doesn't exceed our decimals size if (fraction.length > multiplier.length - 1) { throw Exception( "fractional component exceeds decimals, underflow, parseFixed"); diff --git a/cw_core/test/parse_fixed_test.dart b/cw_core/test/parse_fixed_test.dart new file mode 100644 index 000000000..5ce520166 --- /dev/null +++ b/cw_core/test/parse_fixed_test.dart @@ -0,0 +1,38 @@ +import 'package:cw_core/parse_fixed.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('parseFixed', () { + group('parseFixed, positive', () { + test('should parse 1.000001 as 1000001', + () => expect(parseFixed("1.000001", 6), BigInt.from(1000001))); + + test('should parse 1 as 1000000', () => expect(parseFixed("1", 6), BigInt.from(1000000))); + + test('should parse 1. as 1000000', () => expect(parseFixed("1.", 6), BigInt.from(1000000))); + + test('should parse 1.1 as 1100000', () => expect(parseFixed("1.1", 6), BigInt.from(1100000))); + + test('should parse 01.1 as 1100000', + () => expect(parseFixed("01.1", 6), BigInt.from(1100000))); + + test('should parse 1100000 as 11000000', + () => expect(parseFixed("1100000", 1), BigInt.from(11000000))); + }); + + group('parseFixed, negative', () { + test('should parse -1.000001 as -1000001', + () => expect(parseFixed("-1.000001", 6), BigInt.from(-1000001))); + + test('should parse -1 as 1000000', () => expect(parseFixed("-1", 6), BigInt.from(-1000000))); + }); + + group('parseFixed, no leading 0', () { + test('should parse .000001 as 1', () => expect(parseFixed(".000001", 6), BigInt.from(1))); + + test('should parse .00002 as 20', () => expect(parseFixed(".00002", 6), BigInt.from(20))); + + test('should parse -.00002 as -20', () => expect(parseFixed("-.00002", 6), BigInt.from(-20))); + }); + }); +}