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

This widget is not supported in dev-mode. Kindly enable it or run using yarn webapp:dev-widgets.

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 the Decimal.TryParse() method is called, it returns the decimal value. This value is stored inside n.

Return value

It returns a Boolean value. It returns true if string s was successfully converted. Otherwise, it returns false.

Example

This widget is not supported in dev-mode. Kindly enable it or run using yarn webapp:dev-widgets.

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, and s3 was successful using if and else statements. 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, s2 fails to convert because it does not contain a numerical value.

Free Resources