Decimal Data Type - Visual Basic (original) (raw)

Holds signed 128-bit (16-byte) values representing 96-bit (12-byte) integer numbers scaled by a variable power of 10. The scaling factor specifies the number of digits to the right of the decimal point; it ranges from 0 through 28. With a scale of 0 (no decimal places), the largest possible value is +/-79,228,162,514,264,337,593,543,950,335 (+/-7.9228162514264337593543950335E+28). With 28 decimal places, the largest value is +/-7.9228162514264337593543950335, and the smallest nonzero value is +/-0.0000000000000000000000000001 (+/-1E-28).

The Decimal data type provides the greatest number of significant digits for a number. It supports up to 29 significant digits and can represent values in excess of 7.9228 x 10^28. It is particularly suitable for calculations, such as financial, that require a large number of digits but cannot tolerate rounding errors.

The default value of Decimal is 0.

Programming Tips

Dim decimalValue As Decimal = 1234567890123456789012345D
Dim doubleValue As Double = CDbl(decimalValue)

Console.WriteLine("Decimal value: " & decimalValue)
Console.WriteLine("Double value: " & doubleValue)

The output of the preceding example shows that the Decimal value retains full precision, while the Double value loses precision due to the limitations of the Double data type.

 Decimal value: 1234567890123456789012345
 Double value: 1.23456789012346E+24
Dim d1, d2, d3, d4 As Decimal  
d1 = 2.375D  
d2 = 1.625D  
d3 = d1 + d2  
d4 = 4.000D  
MsgBox("d1 = " & CStr(d1) & ", d2 = " & CStr(d2) &  
      ", d3 = " & CStr(d3) & ", d4 = " & CStr(d4))  

The output of MsgBox in the preceding example is as follows:

d1 = 2.375, d2 = 1.625, d3 = 4.000, d4 = 4  

Range

You might need to use the D type character to assign a large value to a Decimal variable or constant. This requirement is because the compiler interprets a literal as Long unless a literal type character follows the literal, as the following example shows.

Dim bigDec1 As Decimal = 9223372036854775807   ' No overflow.
Dim bigDec2 As Decimal = 9223372036854775808   ' Overflow.
Dim bigDec3 As Decimal = 9223372036854775808D  ' No overflow.

The declaration for bigDec1 doesn't produce an overflow because the value that's assigned to it falls within the range for Long. The Long value can be assigned to the Decimal variable.

The declaration for bigDec2 generates an overflow error because the value that's assigned to it is too large for Long. Because the numeric literal can't first be interpreted as a Long, it can't be assigned to the Decimal variable.

For bigDec3, the literal type character D solves the problem by forcing the compiler to interpret the literal as a Decimal instead of as a Long.

See also