【问题标题】:How to round to nearest int when casting float to int in gogo - 将浮点数转换为int时如何舍入到最近的int
【发布时间】:2016-05-09 00:55:35
【问题描述】:

当将 float 转换为 int 时,小数点被丢弃。什么是一种干净的投射方式,以便它四舍五入到最接近的整数。

x := int(3.6) 应该等于 4 而不是 3。

【问题讨论】:

标签: go


【解决方案1】:

int(f+0.5) 将导致它向上舍入,如果它 >= .5

【讨论】:

  • 这提供了一个类型转换;请注意,未使用术语 cast
  • 此外,如果您希望舍入到 最近的整个整数,则类型转换不适用于负数。
【解决方案2】:

在 Go 中将浮点数转换为整数时,您可以使用 int(math.Round(f)) 舍入到最接近的整数。当浮点数设置为字节或符文时,小数点也会被丢弃。设置为字符串或布尔值时不会发生截断。

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 返回最接近的整数,从零开始四舍五入。见https://golang.org/pkg/math/#Round。见https://stackoverflow.com/a/61503758/12817546

f := 3.6 截断为“uint8 3”,f 为“float64 3.6”,int(Round(f)) 向上舍入为“int 4”,rune(f) 截断为“int32 3”,Sprintf("%.f", f) 为“string 3.6” ”和f != 0 输出“bool true”。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2010-10-28
  • 2018-06-24
  • 1970-01-01
  • 2019-07-24
  • 1970-01-01
  • 1970-01-01
  • 2014-12-08
  • 2013-02-17
相关资源
最近更新 更多