| 1 | import 'package:cw_core/parse_fixed.dart'; |
| 2 | |
| 3 | String formatFixed(BigInt value, int? decimals, {int? fractionalDigits, bool trimZeros = true}) { |
| 4 | decimals ??= 0; |
| 5 | fractionalDigits ??= decimals; |
| 6 | |
| 7 | final multiplier = getMultiplier(decimals); |
| 8 | // Make sure wei is a big number (convert as necessary) |
| 9 | final negative = value.isNegative; |
| 10 | if (negative) { |
| 11 | value = -value; |
| 12 | } |
| 13 | |
| 14 | var fraction = |
| 15 | value.modPow(BigInt.one, BigInt.parse(multiplier)).toString().padLeft(decimals, "0"); |
| 16 | |
| 17 | if (fractionalDigits < 0) { |
| 18 | fractionalDigits = 0; |
| 19 | } |
| 20 | if (fractionalDigits > decimals) { |
| 21 | fractionalDigits = decimals; |
| 22 | } |
| 23 | fraction = fraction.substring(0, fractionalDigits); |
| 24 | |
| 25 | if (trimZeros) { |
| 26 | fraction = removeTrailing("0", fraction); |
| 27 | } |
| 28 | |
| 29 | final whole = value ~/ BigInt.parse(multiplier); |
| 30 | |
| 31 | final valString = fraction.isEmpty ? "$whole" : "$whole.$fraction"; |
| 32 | |
| 33 | if (negative) { |
| 34 | return "-$valString"; |
| 35 | } |
| 36 | |
| 37 | return valString; |
| 38 | } |
| 39 | |
| 40 | String removeTrailing(String pattern, String from) { |
| 41 | if (pattern.isEmpty) { |
| 42 | return from; |
| 43 | } |
| 44 | |
| 45 | var i = from.length; |
| 46 | while (i > 0 && from.startsWith(pattern, i - pattern.length)) { |
| 47 | i -= pattern.length; |
| 48 | } |
| 49 | return from.substring(0, i); |
| 50 | } |