Subscribe

RSS Feed (xml)

C# The Decimal Type

Perhaps the most interesting C# numeric type is decimal, which is intended for use in monetary calculations. The decimal type utilizes 128 bits to represent values within the range 1E28 to 7.9E+28. As you may know, normal floating-point arithmetic is subject to a variety of rounding errors when it is applied to decimal values. The decimal type eliminates these errors and can accurately represent up to 28 decimal places (or 29 places in some cases). This ability to represent decimal values without rounding errors makes it especially useful for computations that involve money.
Here is a program that uses a decimal type in a financial calculation. The program computes the discounted price given the original price and a discount percentage.
// Use the decimal type to compute a discount.

using System;

class UseDecimal {
public static void Main() {
decimal price;
decimal discount;
decimal discounted_price;

// compute discounted price
price = 19.95m;
discount = 0.15m; // discount rate is 15%

discounted_price = price - ( price * discount);

Console.WriteLine("Discounted price: $" + discounted_price);
}
}
The output from this program is shown here:
Discounted price: $16.9575
In the program, notice that the decimal constants are followed by the m or M suffix. This is necessary because without the suffix, these values would be interpreted as standard floating-point constants, which are not compatible with the decimal data type. You can assign an integer value, such as 10, to a decimal variable without the use of the M suffix, though. (A detailed discussion of numeric constants is found later in this chapter.)
Here is another example that uses the decimal type. It computes the future value of an investment that has a fixed rate of return over a period of years.
/*
Use the decimal type to compute the future value
of an investment.
*/

using System;

class FutVal {
public static void Main() {
decimal amount;
decimal rate_of_return;
int years, i;

amount = 1000.0M;
rate_of_return = 0.07M;
years = 10;

Console.WriteLine("Original investment: $" + amount);
Console.WriteLine("Rate of return: " + rate_of_return);
Console.WriteLine("Over " + years + " years");

for(i = 0; i < years; i++)
amount = amount + (amount * rate_of_return);

Console.WriteLine("Future value is $" + amount);
}
}
Here is the output:
Original investment: $1000
Rate of return: 0.07
Over 10 years
Future value is $1967.151357289565322490000
Notice that the result is accurate to many decimal places—more than you would probably want! Later in this chapter you will see how to format such output in a more appealing fashion.

No comments:

Post a Comment

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail