This topic contains 3 replies, has 3 voices, and was last updated by
December 1, 2014 at 2:45 am #20884ParticipantPoints: 0Rank: Member
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 # Why not 0.1?
PS C:\windows\system32> 5.1-4.9 # Why not 0.2?
PS C:\windows\system32> 5.1-4.1
PS C:\windows\system32> 5.1-4.05
PS C:\windows\system32> 96.9-96.1 # Why not 0.8?
PS C:\windows\system32> 96.9-95 # Why not 1.9?
PS C:\windows\system32> 120-100.9
PS C:\windows\system32> 128-126.9 # Why not 1.1?
PS C:\windows\system32> 130-100.9
PS C:\windows\system32> 130-120.9 # Why not 9.1?
December 1, 2014 at 4:32 am #20885ParticipantPoints: 0Rank: Member
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 #20886MemberPoints: 0Rank: Member
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 #20887ParticipantPoints: 0Rank: Member
Many thanks Tim and Dave. That explains.
The topic ‘Simple arithmetic operations with decimals in powershell’ is closed to new replies.