cast from float32 to int in Go
35,819
Just use int()
:
x := float32(3.1)
fmt.Println(int(x))
Which produces 3
as needed, without having to use string conversions or the like.
Author by
Goodwine
Updated on July 05, 2020Comments
-
Goodwine almost 4 years
I have tried several ways to cast a float to an int, what I want is to truncate a float so I only get the integer part. I'm using
x := float32(3.1) y,_ := strconv.Atoi((strconv.Ftoa32(x,'f',0))) //y becomes 3
But if x is 3.9, y will become 4 because this function will round the float32 instead of truncating. Is there a way of truncating instead of rounding? and if so, is it possible to do it without involving strings? (like casting a float to int in C)
-
Goodwine almost 4 yearsLooking back after years, here is why it was confusing -
int(3.2)
fails because the argument is a constant, additionally I was confused around type casting vs type asserting. As a Go newbie this was hard to understand.