integer Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/integer/ Sat, 28 Mar 2020 10:19:58 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 integer Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/integer/ 32 32 159787465 Break number into integer and fraction parts in Go (Golang) https://vikasboss.github.io/break-integer-fraction-part-go/ https://vikasboss.github.io/break-integer-fraction-part-go/#respond Sat, 28 Mar 2020 10:17:04 +0000 https://vikasboss.github.io/?p=1864 Overview math package of GO provides a Modf method that can be used to break a floating-point number into integer and floating part. Please note that the integer part is also returned...

The post Break number into integer and fraction parts in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

math package of GO provides a Modf method that can be used to break a floating-point number into integer and floating part. Please note that the integer part is also returned as a float by this function.

Below is the signature of the function. It takes input as a float number and returns two float64. The first one is the integer part and second is the fractional part.

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

Some points to note about above function

  • The return values int and frac add up to input f
  • int and frac has same sign a input f

Also some special cases of Modf function are

  • Modf(±Inf) = ±Inf, NaN
  • Modf(NaN) = NaN, NaN

Code

package main

import (
    "fmt"
    "math"
)

func main() {
    //Contain both integer and fraction
    integer, fraction := math.Modf(2.5)
    fmt.Printf("Integer: %f. Fraction: %f\n", integer, fraction)

    //Contain only integer part
    integer, fraction = math.Modf(2)
    fmt.Printf("Integer: %f. Fraction: %f\n", integer, fraction)

    //Negative floating point number
    integer, fraction = math.Modf(-2.5)
    fmt.Printf("Integer: %f. Fraction: %f\n", integer, fraction)

    //Contains only fraction part
    integer, fraction = math.Modf(0.5)
    fmt.Printf("Integer: %f. Fraction: %f\n", integer, fraction)
}

Output:

Integer: 2.000000. Fraction: 0.500000
Integer: 2.000000. Fraction: 0.000000
Integer: -2.000000. Fraction: -0.500000
Integer: 0.000000. Fraction: 0.500000

The post Break number into integer and fraction parts in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/break-integer-fraction-part-go/feed/ 0 1864