Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

modulus

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")     } } 
like image 886
John Calder Avatar asked May 14 '13 03:05

John Calder


People also ask

How do you know if a float is whole?

To check if a float value is a whole number with Python, we can use the is_integer method. to check if 1.0 is an integer by calling is_integer on it. It'll return True if it is and False otherwise.

How do you know if a number is a whole number?

html. The Number. isInteger() method in JavaScript is used to check whether the value passed to it is an integer or not. It returns true if the passed value is an integer, otherwise, it returns false.

How do you convert a float to a whole number?

Method 1: Conversion using int(): To convert a float value to int we make use of the built-in int() function, this function trims the values after the decimal point and returns only the integer/whole number part.

Can float take integer values?

Yes, an integral value can be added to a float value. The basic math operations ( + , - , * , / ), when given an operand of type float and int , the int is converted to float first.


1 Answers

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.

like image 97
paxdiablo Avatar answered Sep 28 '22 01:09

paxdiablo