Home >Backend Development >Golang >How Can I Check if a Go float64 Represents a Whole Number?

How Can I Check if a Go float64 Represents a Whole Number?

Susan Sarandon
Susan SarandonOriginal
2024-12-27 15:13:11644browse

How Can I Check if a Go float64 Represents a Whole Number?

Determining Integer Values from Floating Point Numbers in Go

In Go, determining if a float64 represents a whole number can pose a challenge. The modulo operator (%) cannot be used directly on floats.

Solution 1: Comparing Float64 with Integer Equivalent

If your numbers can fit into an int64, consider comparing the float with its converted integer value:

if a == float64(int64(a)) { ... }

Solution 2: Utilizing math.Trunc

For the entire float64 domain, you can use the math.Trunc function:

if a == math.Trunc(a) { ... }

For example:

package main

import (
    "fmt"
    "math"
)

func main() {
    var a float64 = 2.00
    if a == math.Trunc(a) {
        fmt.Println("yay")
    } else {
        fmt.Println("you fail")
    }
}

This code correctly outputs "yay" when a is set to 2.00, indicating that it is a whole number.

The above is the detailed content of How Can I Check if a Go float64 Represents a Whole Number?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn