Motoko convert(Text("123")) to Nat or Int 123?

Text can covert to Nat or Int?

1 Like

I implement it through the following code:

   public func textToNat( txt : Text) : Nat {
        assert(txt.size() > 0);
        let chars = txt.chars();

        var num : Nat = 0;
        for (v in chars){
            let charToNum = Nat32.toNat(Char.toNat32(v)-48);
            assert(charToNum >= 0 and charToNum <= 9);
            num := num * 10 +  charToNum;          
        };

        num;
    };

9 Likes

Awesome! wonderful! You saved my day

1 Like

can we convert in to Nat32? have you any example?

You should just be able to do Nat32.fromNat(result of above function).

Thanks skilesare it works.

To add to the other answers here, the ideal return type for such a function is ?Nat in case the Text input ends up being incompatible with Nat (null).