How to Convert String to Double in PowerShell
Introduction
Converting string to double can be a tricky process. Fortunately, PowerShell provides an easy way to convert string into double and other data types. In this blog post, we’ll take a look at how you can use some commands to convert string into double.
Solution
Using Casting Operator
This method is the easiest and most straightforward way to convert string to double. This method works just like casting in programming languages such as C#, Java, etc. Here’s an example of how this would work:
$string = "3.141"
$num = [Double]$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 double.
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 double.
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 double, we can use following script:
$string = "3.141"
$num = [Convert]::ToDouble($string)
Write-Host $num
Using Parse Method from .NET Framework Double Classes
Another .NET Framework class that can be used is Double
struct. It provides method like Parse
to convert string to double.
$string = "3.141"
$num = [Double]::Parse($string)
Write-Host $num
Using TryParse Method from .NET Framework Double Classes
Besides Parse
method, Double
struct also has a safe method to convert string to double which is TryParse
. This method will check whether the string can be converted to double 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 = [Double]::TryParse($string, [ref]$num)
if ($success) {
Write-Host $num
}
Conclusion
In conclusion, there are several ways to easily convert string into double 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 double. It’s because sometimes we do not know whether the string supplied representing a valid double or not.