AFAIK, we can't use std in Substrate WASM runtime, what is the most effective way to convert a string to a number in runtime.

For example: string "48" in Vec to 48 in u32.

1 Answer 1


While you don't have access to std, you do have access to core, and that should have all the tools you need.

For example, this should work fine inside of the runtime environment:

fn string_to_number(text: Vec<u8>) -> Result<u32, DispatchError> {
    let text_as_string = core::str::from_utf8(&text).map_err(|_| "not a string")?;
    let number: u32 = text_as_string.parse().map_err(|_| "not a number")?;

fn string_to_number_works() {
    let text = "48".as_bytes().to_vec();
    assert_eq!(crate::string_to_number(text).unwrap(), 48);

I am not sure why you would do this though, as parsing text into a number is absolutely not something the runtime is meant to do, and will lead to a bunch of wasted computation and potential user errors.

You should instead do any kind of text parsing in the front-end and only send expected types over to your runtime.

  • Thank you @Shawn Tabrizi for the answer. The reason I did that in runtime is because value stored in the storage of the other pallet is set as Vec<u8>, to use them in different pallet so I would need to convert to u32 to handle the specific logic. Feb 15, 2022 at 2:38
  • For more specific example, one of on-chain attribute of NFT that stored on chain with the format like BTreeMap<Vec<u8>, Vec<u8>> that stored "ArtistFee":"100" (it's a dynamic attribute so no hard-coded properties), I just need to convert "100" to u32 to handle some calculation. Feb 15, 2022 at 2:41
  • If you know any more efficient way or design, really appreciate it if you can share because I am new to Substrate but found it's really awesome framework to work with. Feb 15, 2022 at 2:56
  • 1
    Rather than store the bytes as a string, you should store it as the underlying type, like a Compact<u32>, and then deserialize it as such.
    – Shawn Tabrizi
    Feb 15, 2022 at 6:47

Your Answer

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

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