Simple arithmetic operations with decimals in powershell

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of GJ GJ 2 years ago.

  • Author
    Posts
  • #20884
    Profile photo of GJ
    GJ
    Participant

    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[b][u] # Why not 0.1?[/u][/b]
    0.0999999999999996

    PS C:\windows\system32> 5.1-4.9 [b][u] # Why not 0.2?[/u][/b]
    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 [b] [u]# Why not 0.8?[/u][/b]
    0.800000000000011

    PS C:\windows\system32> 96.9-95 [b] [u]# Why not 1.9?[/u][/b]
    1.90000000000001

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

    PS C:\windows\system32> 128-126.9 [b][u]# Why not 1.1?[/u][/b]
    1.09999999999999

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

    PS C:\windows\system32> 130-120.9 [b][u]# Why not 9.1?[/u][/b]
    9.09999999999999

  • #20885
    Profile photo of Tim Pringle
    Tim Pringle
    Participant

    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

  • #20886
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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
    
  • #20887
    Profile photo of GJ
    GJ
    Participant

    Many thanks Tim and Dave. That explains.

You must be logged in to reply to this topic.