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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With