Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

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

Posted on March 28, 2020March 28, 2020 by admin

Table of Contents

  • Overview
  • Code

Overview

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

  • It returns true for a negative number
  • It returns false for a positive number

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
  • go
  • golang
  • math
  • number
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme