Search code examples
powershelltypesnumber-formatting

Numbers change inside variables for powershell


I am literally just trying to convert a string with week and day information to numbers and store it as variable, yet something really funky is happening, as of now, I have tested this behavior in 4 PCs, and in Powershell 5 and 7 its happening all over the place.

$UP_Down = "6w0d"

[int]$weeks = if ($Up_Down -match "w"){$Up_Down[$($Up_Down.IndexOf('w')-1)]}Else{0}

[int]$days = if ($Up_Down -match "d"){$Up_Down[$Up_Down.IndexOf('d')-1]}Else{0}

[int]$totaldays = (7 * $weeks) + $days

Now the data from the initial variable is obviously 6 weeks and 0 days to which I have to convert to 42 Total days (this is just an example, its happening regardless of combination)

However the following is the Funky results I get which I have elaborated by Write-Output

Weeks If statement results by itself 6
Weeks variable results 54
days If statement results by itself 0
days variable results  48
totaldays variable results are 426

The problem occurs regardless of what numeric datatype I use

Ironically the Variables have the correct value if i DO NOT assign datatype to them, BUT ,

the moment it hits (7*$weeks) even IF the $weeks is correct the value outputted 426, and remember no [int]etc anywhere

What am I doing wrong?


Solution

  • The problem is, that you are not converting the number inside the string "6" to the number 6, but the character '6' to its value according to the underlying character encoding scheme that is 54 in the case of ASCII. Same with the day: '0' has a value of 48. 7 * 54 + 48 = 426.

    See the difference:

    PS C:\Users\name> [int]"6"[0]
    54
    PS C:\Users\name> [int]"6"
    6
    

    When extracting an element of the string through indexing with [0] you get a character instead of a string of length 1. A cast to int will then return the ASCII value of this character.