What is C# decimal type
Description
decimal
is intended for use in monetary calculations.
It utilizes 128 bits to represent values within the range 1E-28
to 7.9E+28
.
decimal
eliminates the rounding errors caused by the normal floating-point data type.
The following code creates a decimal by specifying a Literal decimal,
class MainClass// w w w . j ava 2s. c o m
{
static void Main()
{
System.Console.WriteLine(1.618m);
}
}
The code above generates the following result.
Difference between double and decimal
The following table lists the different between double type and decimal type.
Type | double | decimal |
---|---|---|
Purpose | scitific | financial |
Interal representation | base 2 | base 10 |
Speed | Faster | slower |
An example.
using System;//from ww w . j ava2 s. c o m
class Program
{
static void Main(string[] args)
{
decimal d = 1;
decimal d2 = 0.1M;
Console.WriteLine(d - d2*10);
}
}
The output:
Example
decimal literials
using System;/*w w w.jav a2 s .c o m*/
class Class1
{
static void Main(string[] args)
{
decimal f;
f = 999999999.123456789123456789123456789m;
Console.WriteLine( "{0}", f );
}
}
Decimal implements the following interfaces:
- IComparable
- IConvertible
- IFormattable
The code above generates the following result.
Example 2
Use the decimal type to compute a discount
using System; // www. ja v a 2s. c om
public class MainClass{
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.
Example 3
decimals and arithmetic operators
class MainClass/*from w w w.j a va 2 s . c o m*/
{
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.
Example 4
Use the decimal type to compute the future value of an investment
using System; /* w w w . j a v a 2s .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.