Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if numeric conversion will change value?

Tags:

c#

clr

ieee-754

I'm performing some data type conversions where I need to represent uint, long, ulong and decimal as IEEE 754 double floating point values. I want to be able to detect if the IEEE 754 data type cannot contain the value before I perform the conversion.

A brute force solution would be to wrap a try-catch around a cast to double looking for OverflowException. Reading through certain of the CLR documentation implies that some conversions just silently change the value without any exceptions.

Is there any fool proof way to do this check? I'm looking for completeness over ease of implementation. I have a feeling I'm going to be closely reading the IEEE 754 spec and checking matissa and exponent carefully...

I should add, that I am most concerned with representing whole numbers accurately and that loss of floating point precision is of secondary concern (but still worth considering).

EDIT: Int32 is able to be fully expressed as IEE-754. Also the Decimal data type is very much part of the question.

Important Update: if you are referring to this question, you should also read this question: IEEE-754 Double (64-bit floating point) vs. Long (64-bit Integer) Revisited

It notes a flaw in the answer where some very large values are also able to be exactly represented by IEEE-754. While this may mean that the value will correctly round-trip, for my original purpose (will it round-trip to JavaScript) it will not.

Also there appears to be a bug in the CLRs System.Double type because it doesn't correctly allow these values to round-trip.

like image 330
mckamey Avatar asked Dec 31 '25 18:12

mckamey


1 Answers

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

like image 75
atomice Avatar answered Jan 03 '26 08:01

atomice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!