0

The toHuman() call on Types casts numbers into formatted strings and rounds currency values.

I would like to store large amounts of block information in human-readable format, but not lose the precision of numbers or have them casted into strings.

Is there a way to enjoy the benefits of human-readable objects without having numbers cast into strings and precision lost?

3
  • Can we have some more context? What language are you using? Is this the JavaScript polkadot API or some other API?
    – Gabe
    Jan 20 at 19:33
  • I am referring to vanilla Polkadot.js Jan 20 at 19:57
  • maybe toHex()?
    – kianenigma
    Jan 21 at 20:49

2 Answers 2

1

Try toPrimitive instead and you will get a JS number (when < 2^53 -1) or a string value when it is larger.

Here is an example of it being used to decode an extrinsic. You can see the numbers are not formatted as strings.

If having numbers cast to strings is an issue then use toHex.

2
  • Thanks @forgetso - I'm afraid I need to clarify a part of my question. I tried toPrimitive(), but the issue there is that I'm missing some human-readable parts, like section/method information in an extrinsic. In the toPrimitive() variant, it only gives me the method index. Jan 22 at 20:35
  • Can you edit the question to show your type being formatted? Perhaps sharing the bytes and type may help if it is a common type.
    – forgetso
    Jan 24 at 11:08
0

I solved my issue by monkey patching the toHuman() method of AbstractInt. Now I can call toHuman() on any object and all nested ints will convert the way I need them. Not a clean solution, but in my case it does the job.

import {AbstractInt} from "@polkadot/types-codec/abstract/Int";


AbstractInt.prototype.toHuman = function (isExpanded?: boolean): any {
    if(this.bitLength() <= 64) {
        return this.toPrimitive();
    }
    return this.toBn().toString();
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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