4

Have noticed the following behaviour when trying to compare two doubles.

Given the following basic script:

[double]$maxValue = 1.5
[double]$startValue = 1.2
[double]$counter = $startValue

while ($counter -lt $maxValue) {
    Write-Host $counter
    $counter += 0.1
}

Output:

1.2
1.3
1.4

If i change the while statement to use less than or equals: while ($counter -le $maxValue) {

Output:

1.2
1.3
1.4

Which is exactly the same as above and thus missing the expected last value of "1.5" at the end.

How can i properly compare two doubles in powershell?

mundeep
  • 2,727
  • 1
  • 22
  • 24

1 Answers1

8

I would suggest not using double to start with. Use System.Decimal (which may have an alias in PowerShell - I'm not sure). It looks like you're interested in exact decimal values, so use an appropriate type.

The reason you're not seeing 1.5 is that the closest double to 0.1 is very slightly larger than 0.1... so you're actually getting numbers like 1.2000000001, 1.3000000002, 1.400000002 - and then 1.500000003 is not less than or equal to 1.5.

See my articles on binary floating point and decimal floating point for more information.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks, suspected something like that was going on just couldn't determine what. Looks like decimal does exist, updating the code with [decimal] instead of [double] and it works as expected. – mundeep Mar 02 '12 at 15:48