英文:
How to round to nearest int when casting float to int in go
问题
当将浮点数转换为整数时,小数部分会被舍弃。有没有一种简洁的方法可以将其转换为最接近的整数而不是直接舍弃小数部分。
x := int(3.6)
应该等于4而不是3。
英文:
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.
答案1
得分: 11
int(f+0.5)
如果 f
大于等于 0.5,会向上取整。
英文:
int(f+0.5)
will cause for it to round upwards if it's >= .5
答案2
得分: 9
你可以在Go语言中使用int(math.Round(f))
将浮点数四舍五入为最接近的整数。当将浮点数设置为byte或rune时,小数部分也会被丢弃。当将浮点数设置为字符串或布尔值时,不会发生截断。
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”。
英文:
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”.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论