by Edward
20 August 2009 18:09
I have come across a web site that does not really use validation to check for user input. One of the key validation errors I have seen is the check if a value is int or double. If you don't know, int values are "whole numbers", and cannot a decimal type value, for example "5.5". If you need to store "non-whole numbers", you need to store it either as a double, float or decimal. Decimal should only be used when storing values that needs to be rounded at the second value after the decimal. Rather use double or float. They are lighter, and store values up to one value after the decimal point (e.g. "5.5").
From the MSDN library:
The int keyword denotes an integral type that stores values according to the size and range from -2,147,483,648 to 2,147,483,647.
The double keyword denotes a simple type that stores 64-bit floating-point values. The approximate range for the double type is ±5.0 × 10−324 to ±1.7 × 10308.
As you can see there is a huge difference in terms of the range each value type can handle.
Here is a simple example of how to check if a value entered into a textbox is of type int, or type double.
int intOutput = 0;
if (Int32.TryParse(txtNumericTest.Text, out intOutput))
{
Response.Write("Valid int");
}
else
{
Response.Write("Not a Valid int");
}
//To check Double values
double dOutput = 0;
if (Double.TryParse(txtNumericTest.Text, out dOutput))
{
Response.Write("Valid double");
}
else
{
Response.Write("Not a Valid double");
}