How to Convert String to Decimal in PowerShell

Recently, I was processing a user input in a PowerShell script where I wanted to convert a string to a decimal value. In this tutorial, I will explain how to convert a string to a decimal in PowerShell using different methods with examples.

PowerShell is a dynamically typed language, which means variables don’t require explicit type declarations. However, under the hood, types still matter a great deal—especially when performing mathematical operations.

  • Common numeric types in PowerShell include intdoublefloat, and decimal.
  • The string type holds plain text, which can represent numbers but isn’t recognized as such during calculations.
  • If you try to add a number to a string, you’ll get string concatenation, not arithmetic addition:
$value = "123.45"
$result = $value + 10
# Output: 123.4510

To perform math, explicit conversion to a numeric type like decimal is required.

What is a Decimal in PowerShell?

The [decimal] type in PowerShell represents a fixed-point numeric value, making it ideal for applications that require high-precision calculations, such as financial or scientific computations.

Unlike double, which may introduce rounding errors with certain numbers, decimal maintains higher precision for fractional values.

[decimal]$num = 123.4567

Whenever you deal with currency amounts or any calculation demanding accuracy, prefer using decimals to avoid subtle bugs and rounding mishaps.

Check out Convert Unicode to ASCII using PowerShell

Simple String to Decimal Conversion Syntax

The most direct way to convert a string to a decimal in PowerShell is through casting:

$string = "45.67"
$decimalValue = [decimal]$string
Write-Output $decimalValue

You can see the exact output in the screenshot below:

Convert String to Decimal in PowerShell

PowerShell delegates this conversion to .NET’s robust type conversion system. But keep in mind, if the string doesn’t properly represent a decimal (incorrect decimal point, extra non-numeric character, etc.), this will throw an error.

Also, be aware of locale differences. For instance, some regions use a comma , as the decimal separator. The casting method expects the dot . by default unless otherwise specified.

Check out Convert JSON to XML using PowerShell

Using Parse() Method for Conversion

When you want more control over conversion or need locale awareness, use the [decimal]::Parse() method from .NET.

$strValue = "123.45"
$decimalValue = [decimal]::Parse($strValue)

Here is the exact output:

PowerShell convert string to decimal

This method is strict—any deviation from the expected number format results in an error. This is useful for scripts where data integrity is critical.

To handle different decimal separators, use the System.Globalization.CultureInfo class:

$strValue = "123,45"
$culture = [System.Globalization.CultureInfo]::GetCultureInfo("fr-FR")
$decimalValue = [decimal]::Parse($strValue, $culture)

This feature is crucial when processing international data files.

Read PowerShell Convert Secure String to Plain Text

Safe Conversion with TryParse()

If you want to avoid runtime errors and handle problematic input gracefully, [decimal]::TryParse() is your friend. This method attempts to parse the string and returns True if successful, False otherwise, filling an output variable with the result.

$input = "89.34"
[decimal]$decimalResult = 0
$isValid = [decimal]::TryParse($input, [ref]$decimalResult)
if ($isValid) {
    Write-Output "Converted Value: $decimalResult"
} else {
    Write-Output "Invalid decimal format!"
}

TryParse() is indispensable when processing data from untrusted sources or when validating user input. It keeps your script robust, preventing crashes due to conversion errors.

You can also combine TryParse() and culture info if locale-specific formatting is expected.

Handle Non-Numeric or Invalid Strings

Let’s face it: not all data is clean. You may encounter empty strings, alphabetic characters, or ill-formatted numbers.

  • If you use [decimal]::Parse() with an invalid string (like "abc" or "12x34"), PowerShell will throw an error.
  • With [decimal]::TryParse(), these cases simply return False and allow the script to continue running:
[decimal]::TryParse("abc", [ref]$result) # Returns False, no exception

It’s good practice to validate input before conversion. A simple regular expression or the -match operator can check if a string appears numeric:

if ($str -match '^\d+(\.\d+)?$') {
    # Safe to convert
}

Read Convert String to HTML Table in PowerShell

Formatting and Rounding Decimals

Often, you’ll want to present decimal values rounded or formatted to a specific precision.

Formatting for display:

$value = [decimal]123.456789
"{0:N2}" -f $value  # Output: 123.46

Rounding using .NET’s Math:

[math]::Round($value, 2)  # Output: 123.46

Remember: formatting only affects appearance, while rounding actually changes the value.

Check out Convert a String to Title Case in PowerShell

PowerShell: Convert String to Decimal Examples

Now, let me show you two real examples.

Loop through an array:

Here is another example of converting a string to a decimal while looping through an array.

$stringArray = @("10.5", "20.25", "invalid", "30.75")
$stringArray | ForEach-Object {
    [decimal]$value = 0
    if ([decimal]::TryParse($_, [ref]$value)) {
        Write-Output "Decimal: $value"
    } else {
        Write-Output "Skipping invalid entry: $_"
    }
}

Here is the exact output in the screenshot below:

PowerShell convert string to decimal examples

Working with CSV data:

Here is another example: you can convert to decimal while working with a CSV file.

$data = Import-Csv "sales.csv"
foreach ($item in $data) {
    $item.Amount = [decimal]$item.Amount
}

I hope you now understand how to convert a string to a decimal in PowerShell using various methods with examples. Do let me know if this tutorial helps in the comments below.

You may also like the following tutorials:

Leave a Comment

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.