decimal calculation
In this chapter you will learn:
- Use the decimal type to compute a discount
- decimals and arithmetic operators
- Use the decimal type to compute the future value of an investment
Use the decimal type to compute a discount
using System; //from ja v a 2 s .com
public class Main{
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 code above generates the following result.
decimals and arithmetic operators
class MainClass/*from ja v a 2 s . c om*/
{
public static void Main()
{
System.Console.WriteLine("10m / 3m = " + 10m / 3m);
decimal decimalValue1 = 10;
decimal decimalValue2 = 3;
System.Console.WriteLine( decimalValue1 / decimalValue2);
}
}
The code above generates the following result.
future value of an investment
using System; /*j ava 2 s .c om*/
class Example {
public static void Main() {
decimal amount;
decimal rate_of_return;
int years, i;
amount = 100000.0M;
rate_of_return = 0.17M;
years = 100;
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);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Create decimal literal to create decimal value
- Constructors for decimal
- Create decimal number from double
Home » C# Tutorial » Decimal, Float, Double