Go语言如何检查浮点数值是否实际为整数

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

Go lang how to check if float value is actually int

问题

func isFloatInt(floatValue float64) bool{
//这里的实现是什么?

}

测试用例:
输入:1.5 输出:false;
输入:1 输出:true;
输入:1.0 输出:true;

英文:
func isFloatInt(floatValue float64) bool{
//What's the implementation here?

}

<b>Test cases:</b> <br>
input: 1.5 output: false;<br>
input: 1 output: true;<br>
input:1.0 output: true;<br>

答案1

得分: 15

我刚刚查看了这个代码片段,它对NaN也能正确处理。

func isIntegral(val float64) bool {
    return val == float64(int(val))
}
英文:

I just checked on the playground, this does the right thing with NaN as well.

func isIntegral(val float64) bool {
    return val == float64(int(val))
}

答案2

得分: 10

你可以通过取模运算来实现:

func isFloatInt(floatValue float64) bool {
    return math.Mod(floatValue, 1.0) == 0
}
英文:

You could achieve it by doing a modulus

func isFloatInt(floatValue float64) bool {
	return math.Mod(floatValue, 1.0) == 0
}

huangapple
  • 本文由 发表于 2017年4月3日 18:38:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/43182427.html
匿名

发表评论

匿名网友

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

确定