1. Technology

C# Tutorial - Learn the Fundamentals of Programming

By

5 of 10

Working with Floating Point Numbers

Floating Point Types

C# has support for three floating point types.
  • Float. This has a range of ±1.5x10-45 to ±3.4x1038 with 7 digits of precision.
  • Double. This has a range of ±5.0x10-324 to ±1.7x10308 with 15-16 digits of precision.
  • Decimal. This has a range of ±1.0 × 10-28 to ±7.9 × 1028 with 28-29 digits of precision.
Precision is how many digits are valid in a number. This includes digits before and after the decimal point. So a float value of 19005.6789 with 9 digits gets rounded to 19005.68 . It should be stored as a double instead. Try this code to see that. Then change the float to double, and remove the f from the end of the literal or there will be additional rounding errors because the compiler handles it as a float before it store it in the double variable.
 float f = 19005.6789f;
 Console.WriteLine("Value of is {0}",f) ;
 

Implicit Conversions

The C# compiler is pretty good at doing implicit conversions between numeric types when you assign them or pass them in as parameters to a function. The general rule is that it should do it without causing any loss. This means that a smaller numeric type can be converted to a larger one without warnings. Also If you try to assign a signed number like -9 to an unsigned type, it will be flagged as an error. You can of course force this by doing a cast as we saw earlier.
 int i=-9;
 uint j=i; // error won't compile
 j= (uint)i; // cast- so will compile
 
By using a cast, you are telling the compiler that you know what you are doing and it allows it without warning or error.

You cannot implicitly convert a float or a double to decimal. Presumably this is because both types can hold larger numbers than decimal can hold.

On the next page - Floating Point Continued

  1. About.com
  2. Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Working with Floating Point Numbers

©2014 About.com. All rights reserved.