#floatToInt()

1 messages · Page 1 of 1 (latest)

primal berry
#

Is there any way to determine the maximum and minimum floats that can be stuffed into @floatToInt() without invoking safety-checked undefined behaviour? The float/int combinations are known at compile time - currently f32/int32 & f64/int64.

(I'm currently improving my Zig skills by converting some files in the Lua C source to Zig. The Lua code is good quality with tests - nice to work with.)

silk panther
#

if you look at the source of std.math.lossyCast you'll see one way you could handle that

primal berry
#

@ehass std.math.lossyCast uses @floatToInt which is the problem that I have. I want either a lossless cast (if possible) or a float (if lossy). But you have pointed me to a possible solution with std.math.floatMantissaBits or std.math.floatFractionalBits which should enable me to calculate the maximum lossless integer in a float.

#

n.b. a mantissa is logarithmic - std.math.floatSignificand would be the more correct name for std.math.floatMantissa.

primal berry
#

This is for Lua. Given a lua_Float I need to losslessly convert it to a lua_Integer where possible, otherwise it stays as the lua_Float. The resultant value being pushed onto Lua's stack.

random ginkgo
#

You can check the bounds of an int type with std.math.maxInt and std.math.minInt

#

I was going to suggest you could use std.math.cast to perform a checked cast but apparently that doesn't handle floats, rip

buoyant violet
random ginkgo
#

That's for intToFloat not floatToInt

buoyant violet
#

thats a constant, it works both ways

random ginkgo
#

Well no, not really

#

That constant simply describes the maximum integer a float type can represent at full precision

buoyant violet
#

any float larger than that will have been rounded any may not be the actual integer you were expecting

random ginkgo
#

When casting an int larger than that to that float, it'll be rounded to the nearest representable int

#

But if you have a float larger than that, it's already rounded so no rounding happens during the conversion

random ginkgo