How to check if double can fit into float without converting to infinity

Is there a standard way to check if a 64-bit floating-point number can be converted to 32-bit without converting to +/- Infinity?

I know that it can be checked subsequently for +/- Inf.

Convert.ToSingle() will not do this.

+3
source share
1 answer

To check if double d converts to float without infinity, you can check whether d an absolute value strictly below double , written as 3.4028235677973366e+38 (i.e., 0x1.ffffffp+127 in hexadecimal format). This number is the exact limit between doubles that can be converted to float, and those that cannot.

To expand a bit, the last final float:

 0x1.fffffep+127 (3.4028234663852886e+38 in decimal) 

What will be the following float number if the float type had more exponent bits:

 0x2.000000p+127 (3.4028236692093846e+38 in decimal) 

Numbers that are closer to the first than the last are rounded to the first. The limit is the midpoint of two numbers:

 0x1.ffffffp+127 (3.4028235677973366e+38 in decimal) 
+1
source

Source: https://habr.com/ru/post/976003/


All Articles