How to convert a string to a decimal in C#
Overview
Converting a string to a decimal value or decimal equivalent can be done using the Decimal.TryParse() method.
It converts the string representation of a number to its decimal equivalent. When a value is returned by this method, the conversion was successful.
Syntax
Parameters
-
s: This is the string that we want to convert to a decimal value. -
n: This is a mandatory parameter that is a decimal value. When theDecimal.TryParse()method is called, it returns the decimal value. This value is stored insiden.
Return value
It returns a Boolean value. It returns true if string s was successfully converted. Otherwise, it returns false.
Example
Explanation
-
Lines 10–12: We create some string variables.
-
Line 16: We create a decimal variable that is not yet initialized with a value. It will store the value converted by the
Decimal.TryParse()method. -
Line 19–49: We check if the conversion of string
s1,s2, ands3was successful usingifandelsestatements. If it is successful, then we print the value of the string, the result, and instance type. Otherwise, we say that the conversion failed.
Note: When the code is run,
s2fails to convert because it does not contain a numerical value.