December 1, 2014 at 2:45 am #20884
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
PS C:\windows\system32> 5.1-4
PS C:\windows\system32> 5-4.9[b][u] # Why not 0.1?[/u][/b]
PS C:\windows\system32> 5.1-4.9 [b][u] # Why not 0.2?[/u][/b]
PS C:\windows\system32> 5.1-4.1
PS C:\windows\system32> 5.1-4.05
PS C:\windows\system32> 96.9-96.1 [b] [u]# Why not 0.8?[/u][/b]
PS C:\windows\system32> 96.9-95 [b] [u]# Why not 1.9?[/u][/b]
PS C:\windows\system32> 120-100.9
PS C:\windows\system32> 128-126.9 [b][u]# Why not 1.1?[/u][/b]
PS C:\windows\system32> 130-100.9
PS C:\windows\system32> 130-120.9 [b][u]# Why not 9.1?[/u][/b]
December 1, 2014 at 4:32 am #20885
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.
[decimal] 5 – [decimal] 4.9
December 1, 2014 at 4:34 am #20886
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
December 1, 2014 at 4:48 am #20887
Many thanks Tim and Dave. That explains.
You must be logged in to reply to this topic.