Simple arithmetic operations with decimals in powershell

Hi All -

Before I begin, I am very new to powershell and and just started learning it.

I am trying to do some very basic arithmetic operations (subtractions) in powershell and I am unable to understand the way it works.

The documentations seem to explain more about the arithmetic operations with full numbers and internet explanations talk more about .NET classes which I don’t understand.

Below are the samples -

PS C:\windows\system32> 5-4
1

PS C:\windows\system32> 5.1-4
1.1

PS C:\windows\system32> 5-4.9 # Why not 0.1?
0.0999999999999996

PS C:\windows\system32> 5.1-4.9 # Why not 0.2?
0.199999999999999

PS C:\windows\system32> 5.1-4.1
1

PS C:\windows\system32> 5.1-4.05
1.05

PS C:\windows\system32> 96.9-96.1 # Why not 0.8?
0.800000000000011

PS C:\windows\system32> 96.9-95 # Why not 1.9?
1.90000000000001

PS C:\windows\system32> 120-100.9
19.1

PS C:\windows\system32> 128-126.9 # Why not 1.1?
1.09999999999999

PS C:\windows\system32> 130-100.9
29.1

PS C:\windows\system32> 130-120.9 # Why not 9.1?
9.09999999999999

PowerShell doesnt default to these being decimals though, it defaults to [double] so you need to cast them.

How we interperate numbers and how computers do are different.

So you need to specify a type [decimal] in order to get what you’re looking for.

e.g.

[decimal] 5 - [decimal] 4.9
0,1

Computers represent floating point numbers in binary (base-2), which is sometimes not completely accurate when it tries to express a base-10 decimal number. This is why you should never use floating-point numbers when calculating currency, etc. To address this problem, there is a [decimal] type in the .NET Framework. The internals of how this class fixes the problem are not particularly important; you just need to know how to use it. In this case, you can append the letter “d” to any numeric literal, which tells the PowerShell parser to treat it as a decimal number instead of int or double:

130d-120.9d # 9.1

# etc

Many thanks Tim and Dave. That explains.