uvtc
uvtc

Reputation: 720

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.

Upvotes: 4

Views: 1467

Answers (5)

Bobby Graczyk
Bobby Graczyk

Reputation: 86

I have an even more naive (but even easier) conversion:

var x:haxe.Int64 == 100000000;
var xFloat:Float = haxe.Int64.toInt(x) * 1.0;

Upvotes: 0

Damilare Akinlaja
Damilare Akinlaja

Reputation: 41

You may want to try to use FPHelper class. It contains a set of methods to convert Int types to Float / Double.

import haxe.io.FPHelper;

class Test {
    static function main() {
        var x = haxe.Int64.parseString("1000000000000");
        var f = FPHelper.i64ToDouble(x.low, x.high);
        trace(f);
    }
}

See https://try.haxe.org/#CDa93

Upvotes: 1

azrafe7
azrafe7

Reputation: 2726

Or, for a naive conversion method, you can use:

var f = Std.parseFloat(haxe.Int64.toStr(x));

Upvotes: 2

YellowAfterlife
YellowAfterlife

Reputation: 3172

Alternatively, you can convert Int64 to Float yourself by combining high/low halves:

class Test {
  static function main() {
    var x = haxe.Int64.parseString("1000000000000");
    var f = x.high * 4294967296. + (x.low >>> 0);
    trace("" + x);
    trace(f);
  }
}

Here, 4294967296. is a float literal for unsigned 2^32;
>>> 0 is required because the lower half can be signed.

Upvotes: 2

samcodes
samcodes

Reputation: 1133

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)
    }
}

Upvotes: 4

Related Questions