How to Convert String to Decimal in PowerShell

Introduction

Converting string to decimal can be a tricky process. Fortunately, PowerShell provides an easy way to convert string into decimal and other data types. In this blog post, we’ll take a look at how you can use some commands to convert string into decimal.

Solution

Using Casting Operator

This method is the easiest and most straightforward way to convert string to decimal. This method works just like casting in other programming languages such as C#, Java, etc. Here’s an example of how this would work:


$string = "3.141"
$num = [Decimal]$string

Write-Host $num

Using Convert class from .NET Framework

The second way that we will discuss is by utilizing the .NET Framework classes provided by Microsoft. These classes provide powerful methods for performing various types of data conversion tasks including converting string into decimal.

The most commonly used class is System.Convert which provides several static methods that are specifically designed for converting string into different data types such as decimal or doubles.

To get list of static methods that can be used for conversion, we can use following command:


[Convert] | Get-Member -Static

Later, to convert string to decimal, we can use following script:


$string = "3.141"
$num = [Convert]::ToDecimal($string)

Write-Host $num

Using Parse Method from .NET Framework Decimal Classes

Another .NET Framework class that can be used is Decimal struct. It provides method like Parse to convert string to decimal.


$string = "3.141"
$num = [Decimal]::Parse($string)

Write-Host $num

Using TryParse Method from .NET Framework Decimal Classes

Besides Parse method, Decimal struct also has a safe method to convert string to decimal which is TryParse. This method will check whether the string can be converted to decimal or not while at the same time it will out the conversion result. To do this, we must use ref parameter modifer which is the counterpart of out keyword in C#.


$string = "3.141"
$num = $null
$success = [Decimal]::TryParse($string, [ref]$num)

if ($success) {
    Write-Host $num
}

Conclusion

In conclusion, there are several ways to easily convert string into decimal in PowerShell. While all methods produce the same result, the last method which is using TryParse supposed to be the safest way to convert string to decimal. It’s because sometimes we do not know whether the string supplied representing a valid decimal or not.