web analytics

C# Floating-Point Types

Options

codeling 1595 - 6639
@2016-12-06 12:08:43

The following table shows the precision and approximate ranges for the floating-point types.

Type Approximate range Precision
float ±1.5e−45 to ±3.4e38 7 digits
double ±5.0e−324 to ±1.7e308 15-16 digits
@2016-12-06 12:10:17

float

The float keyword signifies a simple type that stores 32-bit floating-point values. The following table shows the precision and approximate range for the float type.

Type Approximate range Precision .NET Framework type
float -3.4 × 1038to +3.4 × 1038 7 digits System.Single

By default, a real numeric literal on the right side of the assignment operator is treated as double. Therefore, to initialize a float variable, use the suffix f or F, as in the following example:

float x = 3.5F;

If you do not use the suffix in the previous declaration, you will get a compilation error because you are trying to store a double value into a float variable.

@2016-12-06 12:12:27

double

The double keyword signifies a simple type that stores 64-bit floating-point values. The following table shows the precision and approximate range for the double type.

Type Approximate range Precision .NET Framework type
double ±5.0 × 10−324 to ±1.7 × 10308

By default, a real numeric literal on the right side of the assignment operator is treated as double. However, if you want an integer number to be treated as double, use the suffix d or D, for example:

double x = 3D;

 

@2016-12-06 12:14:34

decimal

The decimal keyword indicates a 128-bit data type. Compared to floating-point types, the decimal type has more precision and a smaller range, which makes it appropriate for financial and monetary calculations. The approximate range and precision for the decimal type are shown in the following table.

Type Approximate Range Precision .NET Framework type
decimal (-7.9 x 1028 to 7.9 x 1028) / (100 to 28)

If you want a numeric real literal to be treated as decimal, use the suffix m or M, for example:

decimal myMoney = 300.5m;

Without the suffix m, the number is treated as a double and generates a compiler error.

 

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com