Mohanapriya R Mohanapriya R
Updated date Jul 10, 2024
In this article, we will learn the fundamentals of converting strings to decimals in C#.

Convert Strings to Decimals in C#

C# provides various parsing methods to convert strings into decimal values. The one method is the Decimal.Parse. This method takes a string representation of a number as input and returns its decimal equivalent. 

using System;

class Program
{
    static void Main()
    {
        string stringValue = "123.45";
        decimal decimalValue = Decimal.Parse(stringValue);

        Console.WriteLine($"Original String: {stringValue}");
        Console.WriteLine($"Converted Decimal: {decimalValue}");
    }
}

Output:

Original String: 123.45
Converted Decimal: 123.45

In this example, the string "123.45" is successfully converted to a decimal value using the Decimal.Parse method.

Exception Handling:

It's important to note that parsing methods can throw exceptions if the string does not represent a valid decimal. To handle such scenarios, developers should use exception handling. The Decimal.TryParse method is a safer alternative as it returns a boolean indicating the success of the conversion without throwing an exception.

using System;

class Program
{
    static void Main()
    {
        string stringValue = "abc";
        if (Decimal.TryParse(stringValue, out decimal decimalValue))
        {
            Console.WriteLine($"Converted Decimal: {decimalValue}");
        }
        else
        {
            Console.WriteLine("Invalid input for conversion");
        }
    }
}

Output:

Invalid input for conversion

Comments (0)

There are no comments. Be the first to comment!!!