I want to display a human readable balance with less decimal places like metamask does it. The function formatEther(wei) returns a string, so for proper rounding I need to parse it etc. And I wanted to ask if there is an easier method or best practice how it's done.

enter image description here


Here are two different ways to do it, given str as the string returned by function formatEther:

Option #1:

function truncate(str, maxDecimalDigits) {
    if (str.includes('.')) {
        const parts = str.split('.');
        return parts[0] + '.' + parts[1].slice(0, maxDecimalDigits);
    return str;

Option #2:

const Decimal = require('decimal.js');

function truncate(str, maxDecimalDigits) {
    const num = new Decimal(str);
    return num.toFixed(maxDecimalDigits, Decimal.ROUND_DOWN);

Though probably not critical for your application, see here for a list of rounding modes.

  • Thanks but first solution does not round and second solution uses a library. I'd prefer not to use a library for this. This might be a personal preference – CodingYourLife Jun 5 '20 at 14:50
  • @CodingYourLife: You can use Number(str), then do some arithmetic on this. But knowing the typical magnitude of numeric values in this eco-system, I'm afraid that Number will be potentially less accurate than simply truncating the string, as I have shown in the first option above. – goodvibration Jun 5 '20 at 15:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.