PowerShell Type Conversion
Type conversion is changing a value from one kind to another. A type is the kind of a value, such as a number or a string.
Convert to a whole number
An int cast turns a decimal into a whole number. It rounds to the nearest whole number.
[int]3.9
[int]3.2Convert a number to text
A string cast turns a number into text. The printed result looks the same, but its kind has changed.
[string]42
[string]3.5Let PowerShell convert on its own
Adding a number and a digit string gives a number. Adding text and a number gives text.
1 + "2"
"a" + 1Example
$ageText = "31"
$age = [int]$ageText
$age
$age + 1Key points
- Type: the kind of a value, such as a number or a string.
- Cast: write a type name in square brackets in front of a value to convert it.
- To number: an int cast turns a decimal or a digit string into a whole number.
- To text: a string cast turns a number into text.
- Automatic: PowerShell sometimes converts a value on its own when two kinds are combined.
In this example, the first line stores an age as text. The second line converts that text into a whole number. The last two lines print the age and the age plus one.
Note
an int cast rounds a decimal to the nearest whole number. It does not cut off the decimal part.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What is [int]3.9?