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
Release: 2024-12-27 15:13:11
Original
632 people have browsed it

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)) { ... }
Copy after login

Solution 2: Utilizing math.Trunc

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

if a == math.Trunc(a) { ... }
Copy after login

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")
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template