Validating whole numbers stored as float (was "Inheritance Question")

  • Thread starter Thread starter Neils Christoffersen
  • Start date Start date
N

Neils Christoffersen

Hey all,

I wrote on Friday asking for some help moving a common subclass field up
to the base class (original post and followup included below). This
entails storing whole numbers inside float data types. What I'm stuck on
is how to make sure that the value coming in is indeed a whole number,
without converting it to a string and doing manipulation that way. Is
there a mathematical way to do this?

Thanks again for your help.

--
Neils Christoffersen
(e-mail address removed) (ROT13 to decode)


Original thread:

Neils,

You can use the Pull Up Field refactoring to move the common field from each
child class into the parent class.

http://www.refactoring.com/catalog/pullUpField.html

However before you do that, or while you do that you will need to ensure
that the field is the same type or compatible type (same base type) in each
class. Seeing as an int will fit in a float, I would make the field float
when I pulled it up.

I would consider having a virtual property that the two classes where the
value is an int can override the property to ensure the value stored is
stored as a whole number. This property would be of type float, like the
field. (this would be based on actual business rules).

Closely related to the Pull Up Field refactoring is the Pull Up Method
refactoring:

http://www.refactoring.com/catalog/pullUpMethod.html

To effectively use Refactoring, Martin Fowler's book "Refactoring -
Improving the Design of Existing Code" from Addison Wesley is a must, as he
goes into details on the how & why of each refactoring.

http://www.refactoring.com

Hope this helps
Jay

 
Hi Neils,

Neils Christoffersen said:
Hey all,

I wrote on Friday asking for some help moving a common subclass field up
to the base class (original post and followup included below). This
entails storing whole numbers inside float data types. What I'm stuck on
is how to make sure that the value coming in is indeed a whole number,
without converting it to a string and doing manipulation that way. Is
there a mathematical way to do this?

Perhaps something like this:

public bool IsWholeNumber(float value)
{
return ((value % 1) == 0);
}

You'll probably also want to make sure the value is between
Int32.MaxValue and Int32.MinValue.

Regards,
Dan
 
Neils,
In addition to the % (remainder) operator, you might be able to use some of
the functions in System.Math (such as Math.Floor and Math.Ceiling) as I
would expect if the floor of the number matches the ceiling of a number then
the number must be a whole number. (within a small margin of error as
floating point numbers are inexact).

Also as Daniel stated, checking Int32.MinValue & Int32.MaxValue after the
above check is a good idea.

Hope this helps
Jay
 
Back
Top