How to check whether a floating-point variable is an integer (has no fractional part) in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "math"
)

//
// -----------------------------------------------------------------------------
// Determines whether a float64 contains an integer (no fractional part).
// Uses a small tolerance to safely handle floating‑point precision issues.
// -----------------------------------------------------------------------------
func isInteger(value float64) bool {
    const epsilon float64 = 1e-12

    // math.Floor returns the largest integer <= value
    floored := math.Floor(value)

    // If the difference is extremely small, treat the number as an integer
    return math.Abs(value-floored) < epsilon
}

//
// -----------------------------------------------------------------------------
// Prints a descriptive message for the given float64.
// -----------------------------------------------------------------------------
func printCheck(value float64) {
    fmt.Printf("Checking value: %.15f\n", value)

    if isInteger(value) {
        fmt.Println("Result: The value contains an integer.\n")
    } else {
        fmt.Println("Result: The value contains a floating‑point number.\n")
    }
}

//
// -----------------------------------------------------------------------------
// Entry point demonstrating several example values.
// -----------------------------------------------------------------------------
func main() {
    // Example input values
    var a float64 = 42.0                 // integer-like
    var b float64 = 42.00000000001       // floating-point due to tiny fraction
    var c float64 = 89.0000000000001     // integer-like
    var d float64 = -7.0                 // negative integer-like
    var e float64 = 3.14                 // floating-point

    // Run checks
    printCheck(a)
    printCheck(b)
    printCheck(c)
    printCheck(d)
    printCheck(e)
}


/*
run:

Checking value: 42.000000000000000
Result: The value contains an integer.

Checking value: 42.000000000009997
Result: The value contains a floating‑point number.

Checking value: 89.000000000000099
Result: The value contains an integer.

Checking value: -7.000000000000000
Result: The value contains an integer.

Checking value: 3.140000000000000
Result: The value contains a floating‑point number.

*/

 



answered Sep 10 by avibootz

Related questions

...