Welcome To Golang By Example

Get Integer value of a float in Go (Golang)

Table of Contents

Overview

math package of GO provides a Trunc method that can be used to get integer value of a float

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

func Trunc(x float64) float64

Some special cases of Trunc function are

Code

package main

import (
    "fmt"
    "math"
)

func main() {
    res := math.Trunc(1.6)
    fmt.Println(res)

    res = math.Trunc(-1.6)
    fmt.Println(res)

    res = math.Trunc(1)
    fmt.Println(res)
}

Output:

1
-1
1