How to Check if a number is positive or negative in Golang

In this example, you will learn programs to check number is positive or negative, First using the [if else](/2018/11/learn-golang-tutorials-if-else.html) statement. The second is using the standard library Math Signbit function.

  • Positive numbers are the whole number that is greater than zero ie 1,2,3…
  • Negative numbers are numbers that are lesser than zero, -1,-2
  • Each positive number has a corresponding negative number

To understand the below programs, You have the understanding the following features in Go Language.

Check if the number is positive or negative using the if-else statement in the go example

The below program read the number from a user console and stores it in a variable.

Here are steps to check positive or negative numbers using if-else statements.

  • if the number is greater than zero, the Number is positive
  • if the number is less than zero, the number is negative
  • else, number=0 is executed, zero value printed to console

Here is an example program to check positive or negative numbers.

package main
import (
    "fmt"
)

func main() {
    var number int
    fmt.Print("Enter Number:")
    fmt.Scanln( & number)
    if number < 0 {
        fmt.Printf(" %d is a negative integer.", number)
    } else if number > 0 {
        fmt.Printf("%d  is a positive integer.", number)
    } else {
        fmt.Printf("%d is Zero.", number)
    }
}

output is

Enter Number:4
4  is a positive integer.

Enter Number:-9
 -9 is a negative integer.

Enter Number:0
0 is Zero.

How to check Positive or negative numbers using Golang Math Signbit function

The below program uses Math Signbit function. The Signbit function returns true, if the number is negative, return false for a positive number.

package main
import (
    "fmt"
    "math"
)

func main() {
    var number float64
    fmt.Print("Enter Number:")
    fmt.Scanln( & number)
    isPositive: = math.Signbit(number)
    if isPositive {
        fmt.Printf("%f  is a negative integer.", number)

    } else {
        fmt.Printf(" %f is a positive integer.", number)

    }
}

Output is

Enter Number:25
25.000000 is a positive integer.

Enter Number:-24
-24.000000  is a negative integer.

Conclusion

In this post, you will learn the Go language example to check if a given input integer number is positive or negative with the [if else](/2018/11/learn-golang-tutorials-if-else.html) statement, and with the Math signbit function.