How to Concatenate Strings and Floats in PowerShell

When working with PowerShell scripts, I often need to combine text with numerical values to create meaningful output. As a PowerShell developer, you will frequently get requirements to concatenate strings and floats in PowerShell.

In this tutorial, I will show you multiple methods to concatenate strings and float values in PowerShell, along with practical examples.

Method 1 – Using the Plus (+) Operator

The simplest way to concatenate strings and floats in PowerShell is using the plus (+) operator. This is often the first method that PowerShell beginners learn.

Here’s how you can use the plus operator to concatenate a string with a float:

$employeeName = "John"
$monthlySalary = 4235.75

$output = "Employee " + $employeeName + " earns $" + $monthlySalary + " per month."
Write-Host $output

When you run this script, you’ll get:

Employee John earns $4235.75 per month.

You can see the exact output in the screenshot below:

powershell concatenate string and float

While this method works, it can become cumbersome when combining multiple values. It’s also not the most efficient approach in PowerShell.

Check out How to Concatenate String with Space in PowerShell

Method 2 – Using String Interpolation (Recommended)

The most elegant way to concatenate strings and floats in PowerShell is using string interpolation with double quotes. This method is cleaner and easier to read.

$customerName = "Sarah"
$accountBalance = 1254.68

$output = "Customer $customerName has a balance of $accountBalance in their account."
Write-Host $output

However, you might notice a problem here. PowerShell interprets the dollar sign as the beginning of a variable. To display the actual $ currency symbol, you need to escape it with a backtick (`):

$output = "Customer $customerName has a balance of `$$accountBalance in their account."
Write-Host $output

This will correctly output:

Customer Sarah has a balance of $1254.68 in their account.

Here is the output in the screenshot below:

concatenate string and float powershell

For more complex expressions, you can use the $() subexpression operator:

$price = 29.99
$quantity = 3
$output = "The total cost for $quantity items at `$$price each is `$$(${price} * ${quantity})."
Write-Host $output

This will output:

The total cost for 3 items at $29.99 each is $89.97.

String interpolation is widely recommended for its readability and elegance.

Read Concatenate String and Variable in PowerShell

Method 3 – Using the -f Format Operator

The format operator (-f) gives you precise control over how your float values are displayed when concatenated with strings in PowerShell.

$productName = "Surface Laptop"
$productPrice = 1299.99

$output = 'The {0} costs ${1:N2}' -f $productName, $productPrice
Write-Host $output

Output:

The Surface Laptop costs $1,299.99

You can see the exact output in the screenshot below:

How to Concatenate Strings and Floats in PowerShell

The format specifier N2 formats the number with thousand separators and two decimal places.

Here’s a table of common format specifiers for float values:

Format SpecifierDescriptionExample (1234.567)
F2Fixed-point, 2 decimals1234.57
N2Number with commas, 2 decimals1,234.57
C2Currency with symbol$1,234.57
P2Percentage with 2 decimals123,456.70%
E2Scientific notation1.23E+003

This method is particularly useful when you need to control the exact format of your float values.

Check out Concatenate String with NewLine in PowerShell

Method 4 – Using the Join-String Cmdlet (PowerShell 7+)

If you’re using PowerShell 7 or later, you can take advantage of the Join-String cmdlet:

$cityName = "Chicago"
$temperature = 72.5

$cityName, $temperature | Join-String -Separator " temperature is " -OutputSuffix "°F"

This will output:

Chicago temperature is 72.5°F

The Join-String cmdlet is particularly useful when working with arrays or pipeline data.

Read Concatenate Strings Inside Loops in PowerShell

Method 5 – Using the StringBuilder Class for Efficiency

When you need to concatenate many strings and floats in a loop, the StringBuilder class from .NET provides better performance:

$sb = [System.Text.StringBuilder]::new()

$productName = "MacBook Pro"
$basePrice = 1299.00
$taxRate = 0.0625  # 6.25% sales tax

[void]$sb.Append("Product: $productName`n")
[void]$sb.Append("Base Price: `$$basePrice`n")
[void]$sb.AppendFormat("Tax Rate: {0:P2}`n", $taxRate)
[void]$sb.AppendFormat("Tax Amount: `${0:N2}`n", ($basePrice * $taxRate))
[void]$sb.AppendFormat("Total Price: `${0:N2}", ($basePrice * (1 + $taxRate)))

Write-Host $sb.ToString()

Output:

Product: MacBook Pro
Base Price: $1299.00
Tax Rate: 6.25%
Tax Amount: $81.19
Total Price: $1380.19

This approach is particularly valuable when building large strings or when performance matters.

Check out Concatenate String and Integer in PowerShell

Practical Examples

Now, let me show you some practical examples of concatenating a string and a float in PowerShell.

Example 1: Create a Financial Report

$investments = @(
    @{Name="Google Stock"; Value=10523.75; Growth=0.0825},
    @{Name="Microsoft Stock"; Value=8721.50; Growth=0.0612},
    @{Name="Apple Stock"; Value=12450.25; Growth=0.0945}
)

foreach ($investment in $investments) {
    $growthAmount = $investment.Value * $investment.Growth
    $newValue = $investment.Value + $growthAmount

    "Investment: $($investment.Name)"
    "Current Value: `$$($investment.Value.ToString('N2'))"
    "Growth Rate: $($investment.Growth.ToString('P2'))"
    "Growth Amount: `$$($growthAmount.ToString('N2'))"
    "New Value: `$$($newValue.ToString('N2'))"
    ""
}

Example 2: Weather Reporting Script

$cities = @(
    @{Name="New York"; TempF=68.5; Humidity=0.72},
    @{Name="Los Angeles"; TempF=82.7; Humidity=0.45},
    @{Name="Chicago"; TempF=61.3; Humidity=0.65}
)

foreach ($city in $cities) {
    # Convert Fahrenheit to Celsius: (F - 32) * 5/9
    $tempC = ($city.TempF - 32) * 5/9

    "Weather Report for $($city.Name):"
    "Temperature: $($city.TempF.ToString('N1'))°F / $($tempC.ToString('N1'))°C"
    "Humidity: $($city.Humidity.ToString('P0'))"
    "Heat Index: $(($city.TempF * $city.Humidity).ToString('N1'))"
    ""
}

Handling Float Precision Issues

When working with float values in PowerShell, you might encounter precision issues. For example:

$value = 0.1 + 0.2
Write-Host $value  # Outputs 0.3 in PowerShell, but might not in other languages

If you need exact decimal arithmetic, consider using the [decimal] type instead of [float]:

$price = [decimal]29.99
$quantity = 3
$total = $price * $quantity
"Total cost: `$$total"  # Outputs: Total cost: $89.97

Check out How to Split a String by Semicolon in PowerShell

Tips for Formatting Float Values

When concatenating floats with strings, you might want to control how many decimal places are shown:

$pi = [math]::PI  # 3.14159265358979

# Using .ToString() method
"Pi to 2 decimal places: $($pi.ToString('N2'))"  # Pi to 2 decimal places: 3.14

# Using the -f operator
"Pi to 4 decimal places: {0:N4}" -f $pi  # Pi to 4 decimal places: 3.1416

# Using [string]::Format
"Pi in scientific notation: {0}" -f [string]::Format("{0:E2}", $pi)  # Pi in scientific notation: 3.14E+000

Conclusion

In this tutorial, I explained how to concatenate strings and floats in PowerShell using multiple methods. For simple cases, string interpolation with double quotes is usually the most readable option. When you need more control over the formatting, the format operator (-f) is your best choice.

The StringBuilder class provides better performance for complex string building operations, especially in loops or when working with large datasets.

I hope you found this article helpful. If you have any questions or suggestions, please leave them in the comments below.

You may also like:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

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