×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang math.Trunc() Function with Examples

Golang | math.Trunc() Function: Here, we are going to learn about the Trunc() function of the math package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 04, 2021

math.Trunc()

The Trunc() function is an inbuilt function of the math package which is used to get the integer value of the given value.

It accepts a parameter (x) and returns the integer value of x.

Syntax

func Trunc(x float64) float64

Parameters

  • x : The value whose integer value is to be found.

Return Value

The return type of Trunc() function is a float64, it returns the integer value of the given value.

Special Cases

  • Trunc(±0) = ±0
    If the parameter is ±0, the function returns the same value (±0).
  • Trunc(±Inf) = ±Inf
    If the parameter is ±Inf, the function returns the same value (±Inf).
  • Trunc(NaN) = NaN
    If the parameter is NaN, the function returns the same value (NaN).

Example 1

// Golang program to demonstrate the
// example of math.Trunc() Function

package main

import (
	"fmt"
	"math"
)

func main() {
	fmt.Println(math.Trunc(1))
	fmt.Println(math.Trunc(0.23))
	fmt.Println(math.Trunc(-1))
	fmt.Println(math.Trunc(-0.23))
	fmt.Println(math.Trunc(-1.23))
	fmt.Println(math.Trunc(1.23))
	fmt.Println(math.Trunc(math.Pi))
	fmt.Println(math.Trunc(0))
	fmt.Println(math.Trunc(math.Inf(1)))
	fmt.Println(math.Trunc(math.Inf(-1)))
	fmt.Println(math.Trunc(math.NaN()))
}

Output:

1
0
-1
-0
-1
1
3
0
+Inf
-Inf
NaN

Example 2

// Golang program to demonstrate the
// example of math.Trunc() Function

package main

import (
	"fmt"
	"math"
)

func main() {
	var x float64
	var TruncX float64

	x = 0
	TruncX = math.Trunc(x)
	fmt.Printf("Integer value of %.2f is %.2f\n", x, TruncX)

	x = 0.23
	TruncX = math.Trunc(x)
	fmt.Printf("Integer value of %.2f is %.2f\n", x, TruncX)

	x = 1
	TruncX = math.Trunc(x)
	fmt.Printf("Integer value of %.2f is %.2f\n", x, TruncX)

	x = -123.23
	TruncX = math.Trunc(x)
	fmt.Printf("Integer value of %.2f is %.2f\n", x, TruncX)

	x = -2
	TruncX = math.Trunc(x)
	fmt.Printf("Integer value of %.2f is %.2f\n", x, TruncX)

	x = math.Pi
	TruncX = math.Trunc(x)
	fmt.Printf("Integer value of %.2f is %.2f\n", x, TruncX)
}

Output:

Integer value of 0.00 is 0.00
Integer value of 0.23 is 0.00
Integer value of 1.00 is 1.00
Integer value of -123.23 is -123.00
Integer value of -2.00 is -2.00
Integer value of 3.14 is 3.00

Golang math Package Constants and Functions »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.