Menu Close

Go – How to get integer and fractional part of floating-point numbers in go

Here, We will learn how to get integer and fractional part of floating-point numbers in go. We can get it by using Modf() function in math package in go golang.

Function prototype:

func Modf(num float64) (int float64, frac float64)

Return value:

Modf() function in math package returns 
integer and fractional floating-point numbers
that sum to num.

Example with code:

package main

import (
  "fmt"
  "math"
)

func main() {

  int, float := math.Modf(1.3)
  fmt.Println(int, float)

  int, float = math.Modf(2.3)
  fmt.Println(int, float)

  int, float = math.Modf(10)
  fmt.Println(int, float)

  int, float = math.Modf(-2.9)
  fmt.Println(int, float)

  int, float = math.Modf(0)
  fmt.Println(int, float)
}

Output:

1 0.30000000000000004
2 0.2999999999999998
10 0
-2 -0.8999999999999999
0 0

To learn more about golang, Please refer given below link:

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, math

Leave a Reply

Your email address will not be published. Required fields are marked *