haxe

Convert a haxe.Int64 to a Float?


How can I convert a haxe.Int64 to a Float?

I've got something like

var x = haxe.Int64.parseString("1000000000000");

and I'd like to convert that to a Float. I've looked in the Int64 api docs, have found fromFloat, ofInt, and toInt, but there's no toFloat method in there.


Solution

  • I cannot see that functionality in the Haxe standard library either, I checked Int64 and Int64Helper.

    However the MIT-licensed thx.core library does include an implementation, see below: https://github.com/fponticelli/thx.core/blob/master/src/thx/Int64s.hx#L137

    using haxe.Int64;
    
    class Int64s {
    
      static var zero = Int64.make(0, 0);
      static var one = Int64.make(0, 1);
      static var min = Int64.make(0x80000000, 0);
    
    /**
    Converts an `Int64` to `Float`;
    Implementation by Elliott Stoneham.
    */
      public static function toFloat(i : Int64) : Float {
        var isNegative = false;
        if(i < 0) {
          if(i < min)
            return -9223372036854775808.0; // most -ve value can't be made +ve
          isNegative = true;
          i = -i;
        }
        var multiplier = 1.0,
            ret = 0.0;
        for(_ in 0...64) {
          if(i.and(one) != zero)
            ret += multiplier;
          multiplier *= 2.0;
          i = i.shr(1);
        }
        return (isNegative ? -1 : 1) * ret;
      }
    }
    

    Using the library method worked for me, tested on the JavaScript target like so:

    import haxe.Int64;
    import thx.Int64s;
    
    class Main {    
        public static function main():Void {
            var x:Int64 = haxe.Int64.parseString("1000000000000");
            var f:Float = thx.Int64s.toFloat(x);
            trace(f); // Prints 1000000000000 to console (on js target)
        }
    }