How to convert Text to Float

Hi, I’m using the new functionality of outgoing HTTP requests with Motoko and parsing the json response is not an easy task. Basically, I receive a decimal number that I need to perform mathematical operations with. This number is received in Text format and I can’t figure out how to convert it to Float type…

Does anyone have an idea ?

1 Like

After spending a while on it, I wrote a piece of code that seems to do the trick :

public func textToFloat(t : Text) : async Float {

    var i : Float = 1;
    var f : Float = 0;
    var isDecimal : Bool = false;

    for (c in t.chars()) {
      if (Char.isDigit(c)) {
        let charToNat : Nat64 = Nat64.fromNat(Nat32.toNat(Char.toNat32(c) -48));
        let natToFloat : Float = Float.fromInt64(Int64.fromNat64(charToNat));
        if (isDecimal) {
          let n : Float = natToFloat / Float.pow(10, i);
          f := f + n;
        } else {
          f := f * 10 + natToFloat;
        };
        i := i + 1;
      } else {
        if (Char.equal(c, '.') or Char.equal(c, ',')) {
          f := f / Float.pow(10, i); // Force decimal
          f := f * Float.pow(10, i); // Correction
          isDecimal := true;
          i := 1;
        } else {
          throw Error.reject("NaN");
        };
      };
    };

    return f;
  };
6 Likes