如何在Go中测试一个浮点数是否为整数?

huangapple go评论99阅读模式
英文:

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

问题

我最初尝试了这个,但是%运算符对于float64类型没有定义。

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

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

得分: 39

假设你的数字适合int64,你可以将浮点值与转换后的整数值进行比较,看它们是否相同:

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

或者,如果你需要整个float64的范围,你可以使用math.Trunc函数,像这样:

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

例如,以下代码在Go Playground上的测试中正确输出yay

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")
	}
}
英文:

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

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

Alternatively, if you need the entire float64 domain, you can use the math.Trunc function, with something like:

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

For example, the following code correctly outputs yay, on testing over at the Go playground:

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")
	}
}

答案2

得分: 5

你可以使用math.Modf函数:

const epsilon = 1e-9 // 误差范围
if _, frac := math.Modf(math.Abs(a)); frac < epsilon || frac > 1.0 - epsilon {
    // ...
}

在这里使用epsilon是因为浮点数运算不精确(例如float64(.3)+float64(.6)+float64(.1) != 1)

来自godoc的说明:

> func Modf(f float64) (int float64, frac float64)
> Modf返回与f相加的整数和小数部分的浮点数。两个值与f具有相同的符号。

英文:

You can use the math.Modf function:

const epsilon = 1e-9 // Margin of error
if _, frac := math.Modf(math.Abs(a)); frac &lt; epsilon || frac &gt; 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

得分: 0

如何使用 math.Trunc?它可以将 float64 截断为整数部分。

例如,可以这样使用:

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

请注意浮点数表示的常规限制。您可能希望检查 a.Trunc() 是否在 a 的某个小范围内,以考虑像 1.00000000000000002 这样的值。

英文:

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

得分: 0

我这样解决的:

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

调整因子的位数,例如乘以10000来检查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

得分: 0

只需将您的数字进行向上取整(ceil)或四舍五入(float),并将结果与原始值进行比较。
对我来说,最好的解决方案是:

var a float64 = 2.11
var b float64 = 3.00

fmt.Println(math.Ceil(a) == a) // 3.00 == 2.11; false; a不是整数
fmt.Println(math.Ceil(b) == b) // 3.00 == 3.00; true; b是整数

您可以使用一个函数:

func isWhole(x float64) bool {
  return math.Ceil(x) == x
}
英文:

Just ceil or float your number and compare the result to origin value.
The best solution for me:

var a float64 = 2.11
var b float64 = 3.00

fmt.Println(math.Ceil(a) == a) // 3.00 == 2.11; false; a is not a whole number
fmt.Println(math.Ceil(b) == b) // 3.00 == 3.00; true; b is a whole number

You can use a function:

func isWhole(x float64) bool {
  return math.Ceil(x) == x
}

答案6

得分: -1

我认为以下代码可能会有用,

func main(){
    var (
          a float64
          b float64
          c float64
    ) 
    a = 1.23
    b = float64(int64(a))
    c = a - b
    if c > 0 {
        fmt.Println("不是整数")
    } else {
        fmt.Println("整数")
    }
}
英文:

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 &gt; 0 {
        fmt.Println(&quot;Not a Whole Number&quot;)
    } else {
        fmt.Println(&quot;Whole Number&quot;)
    }
}

huangapple
  • 本文由 发表于 2013年5月14日 11:51:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/16534820.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定