【问题标题】:How to round up in c#如何在c#中四舍五入
【发布时间】:2011-04-10 17:22:28
【问题描述】:

我想在 c# 中总是四舍五入,例如,从 6.88 到 7,从 1.02 到 2,等等。

我该怎么做?

【问题讨论】:

  • 尝试写数学。并充分注意你看到的所有功能
  • 规格不完整。 -1.02 应该变成什么?
  • 简单的谷歌搜索会有所帮助:)
  • 是的,我在谷歌上搜索过,首先是这篇文章...谢谢你的提问。

标签: c# rounding


【解决方案1】:

使用Math.Ceiling()

double result = Math.Ceiling(1.02);

【讨论】:

  • 我看到的第一个。这比使用 awayfromzero 更清楚。谢谢!
  • 更清晰,更正确。 :) AwayFromZero 用于其他用途,在这种情况下会为您中断。
  • 是否有返回intlong 的选项?
  • @henry.dv - 我想知道为什么舍入函数会返回一个以开头的双精度数
【解决方案2】:

使用 Math.Ceiling: Math.Ceiling(value)

【讨论】:

    【解决方案3】:

    如果存在负值,Math.Round 有其他选项(在 .Net Core 3 或更高版本中)。

    我做了一个基准测试(.Net 5/release),Math.Ceiling() 更快更高效。

    Math.Round( 6.88, MidpointRounding.ToPositiveInfinity) ==> 7   (~23 clock cycles)
    Math.Round(-6.88, MidpointRounding.ToPositiveInfinity) ==> -6  (~23 clock cycles)
    
    Math.Round( 6.88, MidpointRounding.AwayFromZero)       ==> 7   (~23 clock cycles)
    Math.Round(-6.88, MidpointRounding.AwayFromZero)       ==> -7  (~23 clock cycles)
    
    Math.Ceiling( 6.88)                                    ==> 7   (~1 clock cycles)
    Math.Ceiling(-6.88)                                    ==> -6  (~1 clock cycles)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      • 2022-08-04
      • 2017-11-26
      相关资源
      最近更新 更多