Welcome To Golang By Example

Check if a number is negative or positive in Go (Golang)

Table of Contents

Overview

math package of GO provides a Signbit method that can be used to check whether a given number is negative or positive.

Below is the signature of the function. It takes input a float and returns a bool

func Signbit(x float64) bool 

Code

package main

import (
    "fmt"
    "math"
)

func main() {
    //Will return false for positive
    res := math.Signbit(4)
    fmt.Println(res)

    //Will return true for negative
    res = math.Signbit(-4)
    fmt.Println(res)

    //Will return false for zerp
    res = math.Signbit(0)
    fmt.Println(res)

    //Will return false for positive float
    res = math.Signbit(-0)
    fmt.Println(res)
}

Output:

false
true
false
false