From 4b6afe1db06cb03365369c4d3e58efc63c31c95b Mon Sep 17 00:00:00 2001 From: julian Date: Mon, 29 May 2023 17:13:45 -0600 Subject: [PATCH] indicate loss of precision in displayed amounts --- lib/utilities/amount/amount_unit.dart | 15 +++++++++++++++ test/utilities/amount/amount_unit_test.dart | 18 ++++++++++++++---- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/lib/utilities/amount/amount_unit.dart b/lib/utilities/amount/amount_unit.dart index f418f5752..275352f53 100644 --- a/lib/utilities/amount/amount_unit.dart +++ b/lib/utilities/amount/amount_unit.dart @@ -134,6 +134,9 @@ extension AmountUnitExt on AmountUnit { // start building the return value with just the whole value String returnValue = wholeNumber.toString(); + // if true and withUnitName is true, we will show "~" prepended on amount + bool didLosePrecision = false; + // if any decimal places should be shown continue building the return value if (places > 0) { // get the fractional value @@ -162,6 +165,13 @@ extension AmountUnitExt on AmountUnit { } if (remainder.length > actualDecimalPlaces) { + // check for loss of precision + final remainingRemainder = + BigInt.tryParse(remainder.substring(actualDecimalPlaces)); + if (remainingRemainder != null) { + didLosePrecision = remainingRemainder > BigInt.zero; + } + // trim unwanted trailing digits remainder = remainder.substring(0, actualDecimalPlaces); } else if (remainder.length < actualDecimalPlaces) { @@ -190,6 +200,11 @@ extension AmountUnitExt on AmountUnit { if (tokenContract != null) { overrideUnit = unitForContract(tokenContract); } + + if (didLosePrecision) { + returnValue = "~$returnValue"; + } + return "$returnValue ${overrideUnit ?? unitForCoin(coin)}"; } } diff --git a/test/utilities/amount/amount_unit_test.dart b/test/utilities/amount/amount_unit_test.dart index 2dcd5125c..7af988def 100644 --- a/test/utilities/amount/amount_unit_test.dart +++ b/test/utilities/amount/amount_unit_test.dart @@ -68,7 +68,17 @@ void main() { coin: Coin.ethereum, maxDecimalPlaces: 8, ), - "10.12345678 ETH", + "~10.12345678 ETH", + ); + + expect( + AmountUnit.normal.displayAmount( + amount: amount, + locale: "en_US", + coin: Coin.ethereum, + maxDecimalPlaces: 4, + ), + "~10.1234 ETH", ); expect( @@ -88,7 +98,7 @@ void main() { coin: Coin.ethereum, maxDecimalPlaces: 9, ), - "10123.456789123 mETH", + "~10123.456789123 mETH", ); expect( @@ -98,7 +108,7 @@ void main() { coin: Coin.ethereum, maxDecimalPlaces: 8, ), - "10123456.78912345 µETH", + "~10123456.78912345 µETH", ); expect( @@ -108,7 +118,7 @@ void main() { coin: Coin.ethereum, maxDecimalPlaces: 1, ), - "10123456789.1 gwei", + "~10123456789.1 gwei", ); expect(