PowerShell: How to Convert String to Double


You can use the following syntax in PowerShell to convert a string variable to a double:

$my_double = [double]$my_string

This particular example converts the string variable named $my_string from a string to a double and saves the result in a variable named $my_double.

By using [double] we are able to convert the string variable to a double.

The following example shows how to use this syntax in practice.

Example: How to Convert String to Double Using PowerShell

Suppose we have a string variable named $my_string that has a value of “53.4”.

We can use the following syntax to create this variable and output its data type:

$my_string = "53.4"
$my_string.GetType().Name

The following screenshot shows how to use this syntax in practice:

We can see that the $my_string variable is currently a string.

We can use the following syntax to create a new variable named $my_double that converts the $my_string variable from a string to a double:

$my_double = [double]$my_string 
$my_double.GetType().Name

The following screenshot shows how to use this syntax in practice:

PowerShell convert string to double

Notice that we’ve successfully converted the string variable to a double.

Now suppose that we perform some mathematical operation on each variable.

For example, suppose we use the following syntax to attempt to add 5 to each variable:

$my_string + 5 
$my_double + 5

The following screenshot shows how to use this syntax in practice:

Since the $my_string variable is a string, when we attempt to add 5 to it we simply append the value “5” to the end of the string to get 53.45.

However, since the $my_double variable is a double, when we attempt to add 5 to it we actually add 5 to the original value of 53.4 to get 53.4 + 5 = 58.4.

Note: If you would instead like to convert a variable from a string to an integer then simply use [int] instead of [double].

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Get Last Item in Array
PowerShell: How to Return Multiple Values from Function
PowerShell: How to Generate Random Number Between Range

Leave a Reply