Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go lang how to check if float value is actually int [duplicate]

Tags:

go

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

}

Test cases:
input: 1.5 output: false;
input: 1 output: true;
input:1.0 output: true;

like image 777
dongyan Avatar asked Nov 29 '22 09:11

dongyan


2 Answers

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))
}
like image 183
babbageclunk Avatar answered Dec 04 '22 13:12

babbageclunk


You could achieve it by doing a modulus

func isFloatInt(floatValue float64) bool {
    return math.Mod(floatValue, 1.0) == 0
}
like image 41
Dovydas Bartkevičius Avatar answered Dec 04 '22 15:12

Dovydas Bartkevičius