web analytics

C# Floating-Point Types

Options
@2017-01-13 00:21:12

The integral types are implicitly converted to decimal and the result evaluates to decimal. Therefore you can initialize a decimal variable using an integer literal, without the suffix, as follows:

decimal myMoney = 300;

There is no implicit conversion between floating-point types and the decimal type; therefore, a cast must be used to convert between these two types. For example:

decimal myMoney = 99.9m;

double x = (double)myMoney;

myMoney = (decimal)x;

 

@2017-01-13 00:23:57

You can also mix decimal and numeric integral types in the same expression. However, mixing decimal and floating-point types without a cast causes a compilation error.

The following example causes a compiler error by trying to add double and decimal variables.

double dub = 9;  
// The following line causes an error that reads "Operator '+' cannot be applied to   
// operands of type 'double' and 'decimal'"  
Console.WriteLine(dec + dub);   
  
// You can fix the error by using explicit casting of either operand.  
Console.WriteLine(dec + (decimal)dub);  
Console.WriteLine((double)dec + dub);  
  

The result is the following error:

Operator '+' cannot be applied to operands of type 'double' and 'decimal'

In the following example, a decimal and an int are mixed in the same expression. The result evaluates to the decimal type.

    public class TestDecimal
    {
        static void Main()
        {
            decimal d = 9.1m;
            int y = 3;
            Console.WriteLine(d + y);   // Result converted to decimal
        }
    }
    // Output: 12.1

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com