excelpowershellnumber-formatting

Why does Add-Content translates the comma separator from .TotalSeconds into a dot separator?


When I use this:

$timer = (Get-Date)
$duration = (New-TimeSpan -Start $timer -End (Get-Date)).TotalSeconds
$time = [math]::Round($duration,2)
Add-Content $file $time

I get:

This is what I want

When I use this:

$timer = (Get-Date)
$duration = (New-TimeSpan -Start $timer -End (Get-Date)).TotalSeconds
$time = [math]::Round($duration,2)
Add-Content $file "some text;$time;some text"

I get:

This is not what I want

How do I still get a comma separator when my $time variable is between other values?

I tried to put the variable between double qoutes:

$timer = (Get-Date)
$duration = (New-TimeSpan -Start $timer -End (Get-Date)).TotalSeconds
$time = [math]::Round($duration,2)
Add-Content $file "some text;""$time"";some text"

Anyone ideas?


Solution

  • Your problem is unrelated to Excel and boils down to the different ways culture-sensitive data types such as fractional numbers are stringified:


    Your symptom implies that your current culture is one where , (comma) serves as the decimal mark, such as fr-FR (French).

    If you want to build a string involving culture-sensitive representations of numbers, instead of PowerShell's string interpolation you can use -f, the format operator, which is culture-sensitive:

    Add-Content $file ('some text;{0};some text' -f $time)
    

    Note that you can achieve the same culture-sensitive stringification for a single numeric variable by calling .ToString() on it (e.g., $time = 1.2; $time.ToString() yields 1,2 in cultures where , is the decimal mark).