13

When casting float to int the decimal is discarded. What's a clean way to cast so that it rounds to the nearest whole number instead.

x := int(3.6) should equal 4 instead of 3.

Levsero
  • 591
  • 1
  • 4
  • 14
  • 5
    Possible duplicate of [Go: Converting float64 to int with multiplier](http://stackoverflow.com/questions/33206059/go-converting-float64-to-int-with-multiplier) – icza Jan 31 '16 at 16:04
  • 3
    Related issue: [math: add a Round function](https://github.com/golang/go/issues/4594) – nwellnhof Jan 31 '16 at 16:12
  • @Akavall edited title, – Levsero Jan 31 '16 at 16:43
  • `int(Round(f))` to round a float to an int. See https://stackoverflow.com/a/62753031/12817546. `float64(i)` to set an int to a float. See https://stackoverflow.com/a/62737936/12817546. –  Jul 09 '20 at 23:35
  • Has this changed? See https://go.dev/play/p/tEKYVunbNd_x. – Torsten Bronger Aug 10 '23 at 15:26

2 Answers2

11

int(f+0.5) will cause for it to round upwards if it's >= .5

Rick-777
  • 9,714
  • 5
  • 34
  • 50
Levsero
  • 591
  • 1
  • 4
  • 14
  • This provides a *type conversion*; please note that the term *cast* is not used. – Rick-777 Feb 01 '16 at 09:12
  • 3
    Also, your type conversion will not work well with negative numbers if you intended the rounding to be to the *nearest* whole integer. – Rick-777 Feb 01 '16 at 09:13
9

You could use int(math.Round(f)) to round to the nearest whole number when converting a float to an int in Go. The decimal is also discarded when a float is set to a byte or a rune. Truncation doesn't happen when it's set to a string or a bool.

package main

import (
  . "fmt"
  . "math"
)

func main() {
  f := 3.6
  c := []interface{}{byte(f), f, int(Round(f)), rune(f), Sprintf("%.f", f), f != 0}
  checkType(c)
}
func checkType(s []interface{}) {
  for k, _ := range s {
     Printf("%T %v\n", s[k], s[k])
  }
}

Round returns the nearest integer, rounding half away from zero. See https://golang.org/pkg/math/#Round. See https://stackoverflow.com/a/61503758/12817546.

f := 3.6 truncates to “uint8 3”, f is “float64 3.6”, int(Round(f)) rounds up to “int 4”, rune(f) truncates to “int32 3”, Sprintf("%.f", f) is “string 3.6” and f != 0 outputs “bool true”.

  • 1
    A boolean, numeric, or string type can be set to another type. For`[]byte` see https://stackoverflow.com/a/62725637/12817546, `int` see https://stackoverflow.com/a/62737936/12817546, `[]rune` see https://stackoverflow.com/a/62739051/12817546, `string` see https://stackoverflow.com/a/62740786/12817546 and for `bool` see https://stackoverflow.com/a/62726854/12817546. –  Jul 07 '20 at 09:27