Motoko's type system & converting between types

I wrote a simple function based on @Kyan’s post that works well enough for me (I didn’t need decimal support):

public func textToNat(t : Text) : ?Nat {
  var n : Nat = 0;
  for (c in t.chars()) {
    if (Char.isDigit(c)) {
      let charAsNat : Nat = Nat32.toNat(Char.toNat32(c) - 48);
      n := n * 10 + charAsNat;
    } else {
      return null;
    };
  };

  return Option.make(n);
};
2 Likes