arealhobo
arealhobo

Reputation: 467

Powershell: Getting 0 from Read-Host and Substring comparison with 0 returns false

Im doing a -eq comparison by having a user enter a 3 digit number. If the first number is equal two 0, I need to set a variable to a value. The issue is, 0 is not equaling 0 and returning false.

If $myNumber = 0

This returns false

$myNumber = Read-Host "Enter Number"
$firstNum = $myNumber.Substring(0,1)
if ($firstNum -eq '0') {write-host "True"} else {write-host "False"}

I tried this and still returns false

$myNumber = Read-Host "Enter Number"
$firstNum = $myNumber.Substring(0,1)
if ([int]$firstNum -eq [int]'0') {write-host "True"} else {write-host "False"}

I tried varying combinations but I can never get it to return true, BUT it works with any other number.

If $myNumber = 7

This returns true

$myNumber = Read-Host "Enter Number"
$firstNum = $myNumber.Substring(0,1)
if ($firstNum -eq '7') {write-host "True"} else {write-host "False"}

What am I doing wrong?

Upvotes: 0

Views: 248

Answers (1)

Walter Mitty
Walter Mitty

Reputation: 18940

The first thing you need to understand is the difference between the number 7 and the character string '007'. Try these exercises.

$s = '007'
if ($s[0] -eq '0') {'007 Starts with zero'} else {'007 Starts with non zero'}

$x = '707'
if ($x[0] -eq '0') {'707 Starts with zero'} else {'707 Starts with non zero'}

$n = 7
if ($n[0] -eq '0') {' 7 Starts with zero'} else {'7 Starts with non zero'}

Next, you need to read from the host without converting numeric input to a number. Try this:

[string]$s = Read-Host 'Input 3 digits'
"Your input was $s"
if ($s[0] -eq '0') {'Input starts with zero'} else {'Input starts with non zero'}

Try inputting 707, then try inputting 007.

Upvotes: 1

Related Questions