How to test if numeric conversion will change value?

帅比萌擦擦* 提交于 2019-12-04 13:59:56

Simple solution could be something like (if x is an int):

if ((int)(double)x != x) { 
  // won't convert
} else {
  // will convert
}

and so on for long, etc.

(double)x will convert x from an int to a double. The (int) then converts it back again. So (int)(double)x converts form an int to a double and then back. Essentially the code is checking that the conversion to double is reversible (and therefore that the double can store the exact value of the int).

This mainly depends on the number range you're operating with. As long as you're within 15 digits (for a double), you should be on the safe side for whole numbers.

Basically, what you need to take into account is the number of significant digits. So as long as you number is smaller than the significant digit limit, it will remain exact; if it gets larger, you'll lose precision (even if those are whole numbers).

So as long as your number is < 2^53, you're usually good.

NawaMan

IEEE 754 Double has 52 bits for mantissa and you are converting from/to integer/long so it quite easy to test. If your integer consume less than 52 bits then it should be convertible without problem to IEEE 754 double.

I assume (I know for sure in case of Java but not C# and lazy to check) that int is 32 bits and long is 64 bits. So for sure int can fit in double without any problem both sign and unsign.

For ulong, you simply if all bits higher than the 52th bit is one like ((aULong && 0xFFF0000000000000) == 0).

For long, you have to bring its sign in to the consideration. Since Long is 2nd-complement but IEEE754 is not (just have negative bit), it think it is safe to just covert negative long to positive (*-1) and check like positive. So, if the long is negative, time it with -1 first (do nothing for positive). Then, Check it like ulong.

Hope this helps.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!