How to test whether a float is a whole number in Go?

寵の児 提交于 2020-01-09 10:59:09

问题


I originally tried this, however the % operator isn't defined for float64.

func main(){
    var a float64
    a = 1.23
    if a%1 == 0{
        fmt.Println("yay")
    }else{
        fmt.Println("you fail")
    }
}

回答1:


Assuming your numbers will fit into an int64, you can just compare the float value with a converted integer value to see if they're the same:

if a == float64(int64(a)) {
    fmt.Println("yay")
} else {
    fmt.Println("you fail")
}

Otherwise you can use the math.Trunc function detailed here, with something like:

if a == math.Trunc(a) {
    fmt.Println("yay")
} else {
    fmt.Println("you fail")
}

That one should work within the entire float64 domain.




回答2:


You can use the math.Modf function:

const epsilon = 1e-9 // Margin of error
if _, frac := math.Modf(math.Abs(a)); frac < epsilon || frac > 1.0 - epsilon {
    // ...
}

epsilon is necessary here since floating point math is not precise (e.g. float64(.3)+float64(.6)+float64(.1) != 1)

From the godoc:

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

Modf returns integer and fractional floating-point numbers that sum to f. Both values have the same sign as f.




回答3:


How about math.Trunc? It truncates a float64 to its whole-number component.

For example, something like:

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

Beware of the usual considerations about floating-point representation limitations. You might wish to check whether a.Trunc() is within some small range of a, to account for values like 1.00000000000000002.




回答4:


I solved it like so:

isWhole := int(value * 100) == int(value) * 100

Adjust the number of digits in the factor, e.g. multiply by 10000 to check 4 digits.




回答5:


I think the following code might be useful,

func main(){
    var (
          a float64
          b float64
          c float64
    ) 
    a = 1.23
    b = float64(int64(a))
    c = a - b
    if c > 0 {
        fmt.Println("Not a Whole Number")
    } else {
        fmt.Println("Whole Number")
    }
}


来源:https://stackoverflow.com/questions/16534820/how-to-test-whether-a-float-is-a-whole-number-in-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!