Using Comma as Decimal Delimiter

by Feb 5, 2014

You may not be aware of this, but PowerShell uses a different decimal delimiter for input and output – which may cause confusions to script users.

When you enter information, PowerShell expects culture-neutral format (using "." as decimal delimiter). When outputting information, it uses your regional setting (so in many countries, a "," is used).

Try for yourself and see if this applies to your culture, too:

$a = 1.5
$a
1,5 

This is good practice, because by using culture-neutral input format, scripts will always run the same, regardless of the culture settings. However, if you want users to be able to use a comma as delimiter, take a look at this script:

function Multiply-LocalNumber
{
      param
      (
            [Parameter(Mandatory=$true)]
            $Number1,

            $Number2 = 10
      )

      [Double]$Number1 = ($Number1 -join '.')
      [Double]$Number2 = ($Number2 -join '.')

      $Number1 * $Number2
} 

A user can run it both ways:

When a user picks the comma, PowerShell actually interprets this as array. That’s why the script joins any array by a ".", effectively converting an array to a number. Since the result of -join is a string, the string needs to be converted to a number, and all is fine.

Of course, this is a hacky trick, and it is always better to educate your users to always use the "." delimiter in the first place.

Twitter This Tip! ReTweet this Tip!