How to round to nearest int when casting float to int in go

前端 未结 2 1256
执笔经年
执笔经年 2020-11-29 13:09

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) sho

相关标签:
2条回答
  • 2020-11-29 14:04

    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”.

    0 讨论(0)
  • 2020-11-29 14:06

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

    0 讨论(0)
提交回复
热议问题