1.7 Working with Floating-Point Numbers

 <  Day Day Up  >  

1.7 Working with Floating-Point Numbers

Your application needs to work with floating-point values and you need to determine the correct type to use.


Technique

If memory is your primary concern and the range of possible values isn't too large, use the float data type. If you need very large values knowing that you need to sacrifice precision, use the double data type. If you need accurate and precise data, use the decimal data type.

Comments

Just as with integral types, choosing the proper floating-point number is essential to creating a robust application. There are two main points to consider when deciding which floating-point data type to choose: size and precision.

The .NET floating-point data types allow you to use exponential notation. For instance, the float data type has a range of +/- 1.5 x 10 “45 to +- 3.4 x 10 38 . Although this range is certainly large, the precision of the float only allows for a maximum of seven digits. Any digits after the seventh digit are simply changed to a 0. For financial applications, this change could result in the improper calculation of money, which could have harsh repercussions from the clients who use your software. If, however, you are programming a video game, you might not need precision greater than seven digits. You might have small side effects but nothing like the side effects a loss of precision on a financial calculation would yield.

The double data type has the largest range of all the floating types. It can contain values in the range of 5.0 x 10 “324 to 1.7 x 10 308 . Its precision is limited to just 15 to 16 digits. Although the precision is larger than that of a float , it still might not be suited for financial calculations.

The decimal data type is the only floating type not based on an IEEE specification; it is an exclusive .NET Framework type. This 128-bit number contains a precision of 28 to -29 digits, which makes it the most precise floating-point type. However, its range isn't as widespread as the double data type. It can contain values in the range from 1.0 x 10 “28 to 7.9 x 10 28 .

To resolve ambiguities when working with floating-point numbers, C# contains a suffix for each type. For instance, if you want to assign a number to a double type, use the suffix d as in 3.14d . To designate a float data type, supercede the number with a f . Finally, to use a decimal number, use the m suffix.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

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