VB Convert to Decimal: How-To & Examples
- Value to convert
- 123.45
- You entered
- Input type
- 1 String=1, Double=2, Integer=3
- You entered
This article explains how to convert values to decimal in Visual Basic (VB.NET and VBA), covering the main conversion functions, their syntax, and when to use each one. You’ll learn the difference between CDec, Convert.ToDecimal, and Decimal.Parse, and see practical examples for each.
Formula
The core conversion in VB is done by the CDec function, which converts an expression to Decimal. The syntax is simply:
CDec(expression)
Where expression is any valid numeric or string expression. The result is a Decimal data type, which is a 128-bit number that can hold up to 28-29 significant digits and is ideal for financial calculations.
Worked Example
Using the calculator above with the default values:
- Input value:
123.45(as a string) - Input type:
String(multiplier = 1) - Formula:
123.45 * 1 - Result:
123.45
If you change the input type to Double, the multiplier becomes 2, so the result would be 246.90. The calculator simply demonstrates the multiplicative factor; in real code you would not multiply—you would call the appropriate conversion function.
Why Convert to Decimal?
In VB, the Decimal type is the go-to for precise numeric operations, especially when dealing with money, measurements, or any value where rounding errors from binary floating-point (like Double or Single) are unacceptable. For instance, 0.1 + 0.2 in a Double yields 0.30000000000000004, but in Decimal it gives exactly 0.3. Converting to decimal ensures accuracy in calculations that require a fixed number of decimal places.
Main Conversion Methods
VB offers several ways to convert to Decimal, each with its own nuances:
CDec(expression)– The classic VB conversion function. It’s concise and works on strings, numbers, and objects. It uses the current culture settings for decimal separators.Decimal.Parse(string)– Converts a string to aDecimal. It throws aFormatExceptionif the string is not a valid number.Convert.ToDecimal(value)– A .NET Framework method that converts various types (includingString,Double,Integer) toDecimal. It’s more explicit and can handleNothing(returns 0).Decimal.TryParse(string, result)– A safe version that returns aBooleanindicating success, avoiding exceptions.
How to Choose the Right Method
The choice depends on your context:
- If you’re writing classic VB (VBA) or want a short, familiar syntax, use
CDec. - If you’re in VB.NET and need to convert from a non-string type (e.g.,
Integer),Convert.ToDecimalis straightforward. - If you’re parsing user input from a text box, use
Decimal.TryParseto handle invalid entries gracefully. - If you need to control formatting (like thousands separators),
Decimal.Parsewith aCultureInfoparameter is best.
Common Mistakes and Pitfalls
Here are frequent errors when converting:
- Ignoring culture:
CDec("123.45")works in en-US, but in locales where the decimal separator is a comma, it will fail. UseDecimal.ParsewithCultureInfo.InvariantCulturefor consistent behavior. - Overflow:
Decimalhas a max value of about 7.9×10^28. Converting a hugeDoublelike1e30will throw anOverflowException. - Trailing zeros:
CDec(1.2300)yields 1.2300, but when displayed it may show 1.23. This is normal. - Null values:
CDec(Nothing)in VB.NET returns 0, but in VBA it may cause an error. Always check forNothingfirst.
Performance and Precision
Decimal is slower than Double for arithmetic because it’s implemented in software, but for most business applications the difference is negligible. The precision is far superior: while Double has 15-16 significant digits, Decimal has 28-29. This makes it ideal for financial calculations, but overkill for scientific computations where performance is critical.
Alternatives to Decimal
If you don’t need the full precision of Decimal, consider:
Integer/Long– For whole numbers, use these for speed and memory.Double– For scientific calculations where a tiny rounding error is acceptable.Currency(VBA only) – A fixed-point type with 4 decimal places, useful for money but with less range thanDecimal.
Frequently Asked Questions
What is the difference between CDec and Convert.ToDecimal?
CDec is a VB-specific function that uses the current culture for parsing, while Convert.ToDecimal is a .NET method that also respects culture but offers more overloads and can handle Nothing gracefully. In practice, they are similar, but Convert.ToDecimal is more consistent across .NET languages.
How do I convert a string with commas to decimal?
If the string uses commas as decimal separators (e.g., “123,45”), you need to specify the appropriate culture. For example: Decimal.Parse("123,45", New CultureInfo("fr-FR")). Alternatively, replace commas with periods and use InvariantCulture.
Why do I get an OverflowException when converting?
This happens when the value is too large for the Decimal type (max ~7.9×10^28) or when converting from a Double that has a fractional part beyond the decimal’s precision. Check the value and consider using Double if it’s extremely large.
Can I convert a boolean to decimal?
Yes, Convert.ToDecimal(True) returns 1, and Convert.ToDecimal(False) returns 0. CDec also works, but it may not be as intuitive.
How do I handle invalid input without exceptions?
Use Decimal.TryParse. It returns True if successful and sets the result, otherwise False. This is the recommended way to parse user input.
Is Decimal the same as a floating-point type?
No. Decimal is a fixed-point type (though it can hold a large range), while Double and Single are binary floating-point. Decimal stores numbers as integers scaled by a power of 10, which is why it avoids binary rounding errors.
Related
Formula used
in val | Value to convert | - | 123.45 | 0 in type | Input type | String=1, Double=2, Integer=3 | 1 | 0 out dec | Decimal result | - | val * type | 2
Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.