简体   繁体   English

Math.Round()十进制C#

[英]Math.Round() decimal c#

I have a TimeSpan , ts . 我有一个TimeSpants

When I use Math.Round(ts.TotalHours,2) it's returning 3,3 and that is correct. 当我使用Math.Round(ts.TotalHours,2)它返回3,3 ,这是正确的。

I want to format my decimal to 3,33 -> 3,5 我想将我的十进制格式设置为3,33 -> 3,5

Like this: 像这样:

3 hours = 3,0
3 hours and 10 minutes = 3,25
3 hours and 20 minutes = 3,5
3 hours and 35 minutes = 3,75
3 hours and 55 minutes = 4

Does any one have a good idea? 有谁有个好主意吗?

If you want to round the the nearest 0.25 you can simply multiply with 4, round, and divide by 4. 如果要四舍五入到最接近的0.25,可以简单地乘以4,四舍五入然后除以4。

public static decimal RoundToQuarter(decimal x)
{
  return Math.Round(x*4)/4;
}

You should also think about which MidPointRounding behavior you want. 您还应该考虑所需的MidPointRounding行为。 ie what happens with values like 1/8 or 3/8 . 即使用1/83/8这样的值会发生什么。 Default is round-to-even, where 1/8 becomes 0 , and 3/8 becomes 0.5 . 默认值为四舍五入,其中1/8变为0 3/8变为0.5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM