Decimal Structure
.NET Framework Class Library
Decimal Structure

Represents a decimal number.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic (Declaration)
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Structure Decimal _
    Implements IFormattable, IComparable, IConvertible, IComparable(Of Decimal),  _
    IEquatable(Of Decimal)
Visual Basic (Usage)
Dim instance As Decimal
C#
[SerializableAttribute]
[ComVisibleAttribute(true)]
public struct Decimal : IFormattable, IComparable, 
    IConvertible, IComparable<decimal>, IEquatable<decimal>
Visual C++
[SerializableAttribute]
[ComVisibleAttribute(true)]
public value class Decimal : IFormattable, 
    IComparable, IConvertible, IComparable<Decimal>, IEquatable<Decimal>
JScript
JScript supports the use of structures, but not the declaration of new ones.

The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal value type is appropriate for financial calculations requiring large numbers of significant integral and fractional digits and no round-off errors. The Decimal type does not eliminate the need for rounding. Rather, it minimizes errors due to rounding. For example, the following code produces a result of 0.9999999999999999999999999999 rather than 1.

Visual Basic
Dim dividend As Decimal = Decimal.One
Dim divisor As Decimal = 3
' The following displays 0.9999999999999999999999999999 to the console
Console.WriteLine(dividend/divisor * divisor)   
C#
decimal dividend = Decimal.One;
decimal divisor = 3;
// The following displays 0.9999999999999999999999999999 to the console
Console.WriteLine(dividend/divisor * divisor);   

When the result of the division and multiplication is passed to the Round method, the result suffers no loss of precision as the following code shows.

Visual Basic
Dim dividend As Decimal = Decimal.One
Dim divisor As Decimal = 3
' The following displays 1.00 to the console
Console.WriteLine(Math.Round(dividend/divisor * divisor, 2))   
C#
decimal dividend = Decimal.One;
decimal divisor = 3;
// The following displays 1.00 to the console
Console.WriteLine(Math.Round(dividend/divisor * divisor, 2));   

A decimal number is a floating-point value that consists of a sign, a numeric value where each digit in the value ranges from 0 to 9, and a scaling factor that indicates the position of a floating decimal point that separates the integral and fractional parts of the numeric value.

The binary representation of a Decimal value consists of a 1-bit sign, a 96-bit integer number, and a scaling factor used to divide the 96-bit integer and specify what portion of it is a decimal fraction. The scaling factor is implicitly the number 10, raised to an exponent ranging from 0 to 28. Therefore, the binary representation of a Decimal value is of the form, ((-296 to 296) / 10(0 to 28)), where -296-1 is equal to MinValue, and 296-1 is equal to MaxValue.

The scaling factor also preserves any trailing zeroes in a Decimal number. Trailing zeroes do not affect the value of a Decimal number in arithmetic or comparison operations. However, trailing zeroes can be revealed by the ToString method if an appropriate format string is applied.

Conversion Considerations

This type provides methods that convert Decimal values to and from SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, and UInt64. Conversions from these integral types to Decimal are widening conversions that never lose information or throw exceptions.

Conversions from Decimal to any of the integral types are narrowing conversions that round the Decimal value to the nearest integer value toward zero. Some languages, such as C#, also support the conversion of Decimal values to Char values. If the result of these conversions cannot be represented in the destination type, an OverflowException is thrown.

The Decimal type also provides methods that convert Decimal values to and from Single and Double. Conversions from Decimal to Single or Double are narrowing conversions that might lose precision but not information about the magnitude of the converted value. The conversion will not throw an exception.

Conversions from Single or Double to Decimal throw an OverflowException if the result of the conversion cannot be represented as a Decimal.

Implemented Interfaces

This type implements interfaces IComparable, IComparable<(Of <(T>)>), IFormattable, and IConvertible. Use the Convert class for conversions instead of this type's explicit interface member implementation of IConvertible.

The following code example demonstrates the use of Decimal.

Visual Basic
' Keeping my fortune in Decimals to avoid the round-off errors.
Class PiggyBank
    Protected MyFortune As Decimal

    Public Sub AddPenny()
        MyFortune = [Decimal].Add(MyFortune, 0.01D)
    End Sub

    Public ReadOnly Property Capacity() As Decimal
        Get
            Return [Decimal].MaxValue
        End Get
    End Property

    Public ReadOnly Property Dollars() As Decimal
        Get
            Return [Decimal].Floor(MyFortune)
        End Get
    End Property

    Public ReadOnly Property Cents() As Decimal
        Get
            Return [Decimal].Subtract(MyFortune, [Decimal].Floor(MyFortune))
        End Get
    End Property

    Public Overrides Function ToString() As String
        Return MyFortune.ToString("C") + " in piggy bank"
    End Function
End Class
C#
    /// <summary>
    /// Keeping my fortune in Decimals to avoid the round-off errors.
    /// </summary>
    class PiggyBank {
        protected decimal MyFortune;

        public void AddPenny() {
            MyFortune = Decimal.Add(MyFortune, .01m);
        }

        public decimal Capacity {
            get {
                return Decimal.MaxValue;
            }
        }

        public decimal Dollars {
            get {
                return Decimal.Floor(MyFortune);
            }
        }

        public decimal Cents {
            get {
                return Decimal.Subtract(MyFortune, Decimal.Floor(MyFortune));
            }
        }

        public override string ToString() {
            return MyFortune.ToString("C")+" in piggy bank";
        }
    }
Visual C++
   /// <summary>
   /// Keeping my fortune in Decimals to avoid the round-off errors.
   /// </summary>
   public ref class PiggyBank
   {
   protected:
      Decimal MyFortune;

   public:
      void AddPenny()
      {
         MyFortune = System::Decimal::Add( MyFortune, Decimal(.01) );
      }

      System::Decimal Capacity()
      {
         return MyFortune.MaxValue;
      }

      Decimal Dollars()
      {
         return Decimal::Floor( MyFortune );
      }

      Decimal Cents()
      {
         return Decimal::Subtract( MyFortune, Decimal::Floor( MyFortune ) );
      }

      virtual System::String^ ToString() override
      {
         return MyFortune.ToString("C")+" in piggy bank";
      }
   };
}
JScript
    /// <summary>
    /// Keeping my fortune in Decimals to avoid the round-off errors.
    /// </summary>
    class PiggyBank {
        protected var MyFortune : Decimal;

        public function AddPenny() {
            MyFortune = Decimal.Add(MyFortune, 0.01);
        }

        public function get Capacity() : Decimal {
                return Decimal.MaxValue;
        }

        public function get Dollars() : Decimal {
            return Decimal.Floor(MyFortune);
        }

        public function get Cents() : Decimal {
            return Decimal.Subtract(MyFortune, Decimal.Floor(MyFortune));
        }

        public function ToString() : String {
            return MyFortune.ToString("C")+" in piggy bank";
        }
    }

All members of this type are thread safe. Members that appear to modify instance state actually return a new instance initialized with the new value. As with any other type, reading and writing to a shared variable that contains an instance of this type must be protected by a lock to guarantee thread safety.

Caution noteCaution:

Assigning an instance of this type is not thread safe on all hardware platforms because the binary representation of that instance might be too large to assign in a single atomic operation.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Decimal Sample Using PowerShell      Thomas Lee   |   Edit   |   Show History
<#
.SYNOPSIS
Demonstrates Decimal arithmetic.
.DESCRIPTION
This script Creates two decimals, then multiplys them and
displays them.
.NOTES
File Name : get-decimal1.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell V2 CTP3
.LINK
http://www.pshscripts.blogspot.com
Posted on msdn:
http://msdn.microsoft.com/en-us/library/system.decimal.aspx
.EXAMPLE
PS c:\foo> .\get-decimal1.ps1
$d1 is of type: Decimal
$d2 is of type: Decimal
$d1 (12.1) multiplied by $d2 (12.2) equals: 146.41
$d3 is of type: Decimal
#>
##
# Start of script
##

# Create decimal numbers ($d1, $d2)
[decimal] $d1 = 12.1
[decimal] $d2 = 12.2
# Create product
$d3 = $d1*$d1
# print details
"`$d1 is of type: {0}" -f $d1.gettype().name
"`$d2 is of type: {0}" -f $d2.gettype().name
"`$d1 ({0}) multiplied by `$d2 ({1}) equals: {2}" -f $d1,$d2,$d3
"`$d3 is of type: {0}" -f $d3.gettype().name
# End of script
Processing
Page view tracker