36

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)

nexneo
  • 1,169
  • 2
  • 11
  • 20
Goodwine
  • 1,658
  • 1
  • 18
  • 31

1 Answers1

63

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.

Chris Bunch
  • 87,773
  • 37
  • 126
  • 127
  • 3
    Looking 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. – Goodwine Jul 06 '20 at 08:05