I'm having struggle trying to figure out why some times the substraction of two rounded values gives me a non-rounded value. Is like if 2.2 - 1.1 = 1.10000001.
I have this block of a script in PowerShell:
foreach($disk in $disks)
{
$size = $disk.Size
$freespace = $disk.FreeSpace
$percentFree = [Math]::Round(($freespace / $size) * 100)
$sizeGB = [Math]::Round($size / 1073741824, 2)
$freeSpaceGB = [Math]::Round($freespace / 1073741824, 2)
$usedSpaceGB = $sizeGB - $freeSpaceGB
#view the variable values in every iteration
Write-Debug "`$size = $size"
Write-Debug "`$freespace = $freespace"
Write-Debug "`$percentFree = $percentFree%"
Write-Debug "`$sizeGB = $sizeGB"
Write-Debug "`$freeSpaceGB = $freeSpaceGB"
Write-Debug "`$usedSpaceGB = $usedSpaceGB"
}
The troubling part is:
$usedSpaceGB = $sizeGB - $freeSpaceGB
The [Math]::Round() method seems to work as intended, because I can see the rounded values stored in $sizeGB and $freeSpaceGB variables. Here are some debug output examples:
- I don't understand why in some cases the subtraction of two previously rounded values results in a non-rounded value as you can see in example images.
- This behavior happens in the same exact positions of the loop, lets say in the 7, 10 and 18 iteration.
I export this data to an HTML file so the table looks odd with this values not rounded:
Right now I "fixed" this by Rounding also the subtraction result but I'm wondering why is this happening. I hope someone can help me to understand what is going on.