在 C# 中向上或向下舍入值
我创建了一个在游戏结束时给出分数的游戏,但问题是这个分数有时是一个小数点后有很多位的数字(如 87.124563563566)。我该如何向上或向下舍入该值,以便得到类似 87.12 的值?
谢谢!
I've created a game which gives a score at the end of the game, but the problem is that this score is sometimes a number with a lot of digits after the decimal point (like 87.124563563566). How would I go about rounding up or down the value so that I could have something like 87.12?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
使用
Math.Ceiling(87.124563563566)
或Math.Floor(87.124563563566)
始终向上或向下舍入。我相信这会是最接近的整数。Use
Math.Ceiling(87.124563563566)
orMath.Floor(87.124563563566)
for always rounding up or rounding down. I believe this goes to the nearest whole number.尝试使用 Math.Round。它的各种重载允许您指定所需的位数以及您希望它对数字进行舍入的方式。
Try using Math.Round. Its various overloads allow you to specify how many digits you want and also which way you want it to round the number.
始终向下舍入至小数点后两位:
始终向上舍入至小数点后两位:
To always round down to 2 decimal places:
To always round up to 2 decimal places:
您只想格式化字符串,而不是破坏乐谱。
You just want to format the string, not to corrupt the score.
对于
double
类型的变量来说,这个数字很好,并且在数学上是正确的。您有两个完善的解决方案来避免此类情况。
Math
库。如果您想知道为什么会看到这个“奇怪”的数字,您可以在那里阅读:无理数
The number is fine for
double
type of variable, and mathematically correct.You have two well establish solutions to avoid the such situations.
Math
library.I you want to know why you see this "weird" number, you can read there : irrational numbers
我没有足够的声誉来添加评论,所以我必须创建一个答案。
但 timurid 是对的,只需格式化字符串即可。
我认为您正在寻找的是:
此处描述了一些格式化值的自定义方法:
https://msdn.microsoft.com/en- US/library/7x5bacwt(v=vs.80).aspx
I do not have enough reputation to add comments, so I have to create an answer.
But timurid is right, just format the string.
I think the thing you are looking for is:
Some of the custom ways to format your values are described here:
https://msdn.microsoft.com/en-US/library/7x5bacwt(v=vs.80).aspx
许多人提倡使用数学库对数字进行舍入,但即使这样也可能会导致非常小的舍入误差。
Math.Round 可以并且有时确实返回带有多个尾随零和非常小的舍入误差的数字。这是因为,在内部,浮点数和双精度数仍然表示为二进制数,因此通常很难干净地表示某些小的十进制数。
您最好的选择是仅使用字符串格式,或者如果您确实希望它实际舍入,请将两者结合起来:
A lot of people are advocating you use the Math library to Round your number, but even that can result in very minor rounding errors.
Math.Round can, and sometimes does return numbers with a number of trailing zeros and very small round off errors. This is because, internally, floats and doubles are still represented as binary numbers, and so it can often be hard to represent certain small decimal numbers cleanly.
Your best option is to either only use string formating or, if you do want it to actually round, combine the two: