Order Matters

by Dec 29, 2008

Here is a challenge for you. The following code is a simple currency converter. However, when you run it, you'll notice it doesn't convert correctly. Instead, you always get back the result you entered:

$number = Read-Host 'Enter amount in US dollars'
$rate = 0.7
$result = $number * $rate
"$number USD equals $result EUR"

As it turns out, $number is really a string variable because Read-Host doesn't care what you type in and always returns it as text.


So when you multiply the string with the conversion rate in $rate, a string multiplication occurs. 0.7 becomes a 1, and this leaves the string the way it is.

There are two remedies which highlight different aspects:

You need to either manually cast the result from Read-Host to a double value like this:

$number = [Double] (Read-Host 'Enter amount in US dollars')

Or, you need to change the order when you multiply:

$result = $rate * $number

Whenever you calculate with different object types, PowerShell looks at the type of the first object. If you make sure this object is a number, and $rate is a number, then it will automatically convert the second object to the same type.