<p>Any explanation?
Thanks.</p>
<hr/>**评论:**<br/><br/>emersion_fr: <pre><p>Go 1.10 will have a math.Round function.</p></pre>cdoxsey: <pre><p>There's a long history on this issue: <a href="https://github.com/golang/go/issues/20100">https://github.com/golang/go/issues/20100</a></p>
<p>I think the discussion got mired in the fact that there are different ways to round numbers. int(x+0.5) is a simple workaround.</p></pre>emersion_fr: <pre><p>Note that this workaround doesn't work with negative numbers. See <a href="/u/Zy14rk">/u/Zy14rk</a>'s reply for a correct solution.</p></pre>kerakk19: <pre><p>Thanks for that workaround, didn't even thought about it.</p></pre>anonfunction: <pre><p>Shameless plug: I have a stats package with round and lots of other common functions. </p>
<p>It's open source on github: https//github.com/montanaflynn/stats</p></pre>Zy14rk: <pre><p>Because reasons! So there!</p>
<p>Honestly, I don't know. Seems like such a natural thing to include. Maybe in 2.0 :)</p>
<p>Meanwhile:</p>
<pre><code>func round(num float64) int {
return int(num + math.Copysign(0.5, num))
}
</code></pre></pre>sh41: <pre><p>This should also work:</p>
<pre><code>// round rounds f to a nearby int.
func round(f float64) int {
if f >= 0 {
return int(f + 0.5)
} else {
return int(f - 0.5)
}
}
</code></pre></pre>belak51: <pre><p>These implementations don't quite work, as described in the issue. This will round 0.5 to 1 (and -0.5 to -1) which probably isn't what's intended. </p>
<p>This is probably why the proposal was accepted. There are lots of edge cases and it's easy to have mostly working versions which are still subtly broken.</p></pre>sh41: <pre><p>Well, it does what the comment says, round to a nearby int. It didn't promise rounding towards zero. But I agree, a more well behaved round func would be more complex.</p></pre>sh41: <pre><p>Round what type to what type?</p></pre>kerakk19: <pre><p>Well, most obvious is the float64 to int, but can be also float64 to float64, with declared round point(default .5) and amount of decimal places </p></pre>Fireynis: <pre><p>Rounding is not an easy task to generalize. There are so many types of rounding. Really there should be like 10 round functions not just one. Check out bankers rounding.</p></pre>pobody: <pre><p>That's funny, every other language in the past 30 years has managed it. Seems like it would be a solved problem by now.</p></pre>Fireynis: <pre><p>I'm not saying it's not solvable, nor is it poorly defined. But it's as simple as > 5 round up. </p></pre>slowratatoskr: <pre><p>it's like asking why go doesn't have generics</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传