Comparing Numeric Types


Comparing numeric types is one of the primary ways of building conditional statements. In a comparison of numeric types, one checks to see if a variable's number is less than, equal to, greater than, or not equal to the value stored in another variable or to a literal value.

To compare two numeric types:

  1. Type the name of a variable to store the result of the comparison of type bool . For example: bool bResult = .

  2. Type the name of the variable to use for the first element in the comparison. The variable could be of any of the following types: byte , short , long , int , float , double , decimal , sbyte , ushort , ulong , etc.

  3. Type a comparison operator. The comparison operator could be < (less than), <= (less than or equal to), > (greater than), >= (greater than or equal to), == (equals to), or != (not equal to).

  4. Type a variable name or the literal value for the second element in the comparison.

  5. Type a semicolon ; ( Figure 3.5 ).

    Figure 3.5 You can compare variables to literal numbers , to constants or to other variables. You can also compare a variable to the result of a function, for example. The result of the comparison is true or false.
     int qty = 10; bool validQty = (  qty > 0  ); //validQty will be true double balance = 0.0; const double ZeroBalance = 0.0; bool validBalance = (  balance != ZeroBalance  );                     //validBalance will be false int age1=15; int age2=30; bool Person1Older = (  age1 > age2  );                     //Person1Older will be false 

graphics/tick.gif Tip

  • The type for the second element doesn't have to match the type of the first element. You could, for example, compare an integer to a float, a byte to a double, a float to a double, etc. The only exception is that you can't compare the decimal type to a float or a decimal to a double without casting one of the variables to the type you are comparing against ( Figure 3.6 ).

    Figure 3.6 You can perform some comparisons of numeric types even if the types aren't the same for both variables. One exception is comparing decimals to doubles. In that case a conversion (or casting) is required.
     int x=10; double y = 30.54; decimal z = 11.11M; if (  x<y  ) {    //does not require explicit casting } if (  (double)z < y  ) {    //requires explicit casting } 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net