Home > OS >  rounding double to currency string outputs for crypto currencies
rounding double to currency string outputs for crypto currencies

Time:06-17

current situation and issue

I currently have an issue to display the available amount of a crypto currency in my wallet in a meaningful way. the issue is that the usd equivalents of the cryptos are differing immensly and thus the required precisions are varying a lot.

For instance, lets say I have 50 USD worth in any given cryptocurrency of my wallet. At the time of writing, this would look like the following:

currency shib usdt btc
amount (50 usd each) 6273525.72145... 50 0.0023707‬

in a real world example, it looks like the following:
enter image description here

existing solution (for classic currencies)

Lets say I go for a classic formatting of currencies:

currency.ToString("0.##");
currency shib usdt btc
amount 6273525.72 50.00 0.00

while this would work great for currencies such as shib or usdt, currencies with higher value such as btc or eth will have problems with this:
enter image description here

pseudo-code/solution

I think it would be feasible to go with 3 digits of precision for the first significant digit after the comma:

if (amount >= 1)
{ // in a range to show 2 decimals
    string result = amount.ToString("0.##"); // eg 5.93
}
else
{ // truncate to precision of 3
    // 0.0184432468325 -> "0.0184"
    // 0.00237392482309 -> "0.00237"
    // 0.00043930984274 -> "0.000439"
    // 0.00000000001279 -> "0.0000000000127"
    // 0.123000004234 -> "0.123"
}

how would I go about the last part (if amount is smaller 0)?

CodePudding user response:

Unsure this is a good approach or not, you may look for regex.

Regex 101 with Sample Test Data

^(0.0*\d{1,3})

The above regex captures the group amount with a pattern starting with "0.", has zero or more "0" and lastly any numeric characters with at least 1 and up to 3 occurrences.

public static string TruncateSmallerZeroCryptoAmt(double amount)
{
    Regex regex = new Regex("^(0.0*\\d{3})");
    var match = regex.Match(String.Format("{0:F20}", amount));
        
    return match.Value.TrimEnd('0');
}

The reason why is to convert double to string with a formatting pattern so that the output string will not have E (exponential).

While .TrimEnd('0') is to remove the extra zeros at the back due to previous formatting.

For example:

0.300 --> Display as 0.3

Sample .NET Fiddle

  • Related