开发者

How to round up in c#

开发者 https://www.devze.com 2023-02-23 04:02 出处:网络
I want to round up always in c#, so for ex开发者_运维问答ample, from 6.88 to 7, from 1.02 to 2, etc.

I want to round up always in c#, so for ex开发者_运维问答ample, from 6.88 to 7, from 1.02 to 2, etc.

How can I do that?


Use Math.Ceiling()

double result = Math.Ceiling(1.02);


Use Math.Ceiling: Math.Ceiling(value)


If negative values are present, Math.Round has additional options (in .Net Core 3 or later).

I did a benchmark(.Net 5/release) though and Math.Ceiling() is faster and more efficient.

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消