首页  ·  知识 ·  编程语言
微软.NET精简框架(NETCF)最常见问题(4)
佚名  www.weste.net  .NET  编辑:dezai  图片来源:网络
7.40. How do I round floating point numbers efficiently? There are two primary methods for rounding numbers: Convert.ToInt32

7.40. How do I round floating point numbers efficiently?

There are two primary methods for rounding numbers:

Convert.ToInt32
Cast or Fix (C# or VB)
Convert.ToInt32 automatically handles rounding, where remainders of .5 and greater cause the number to be rounded up. Casting or using Fix requires adding .5 to the number to ensure that it will round properly, as these methods simply remove the remainder.

Profiling on the emulator and a Compaq iPAQ H3600 series device yielded the following results for 1 million operations of each method, where num is a float set to 3.6F:

 

 Emulator
 

 iPAQ
 

 
Operation
 Debug (ms)
 Release (ms)
 Debug (ms)
 Release (ms)
 
C#: Convert.ToInt32(num)
 1321
 1109
 6264
 6283
 
C#: (int)(num + .5F)
 170
 49
 1479
 59
 
VB: Convert.ToInt32(num)
 1218
 1232
 6531
 6517
 
VB: Fix(num + .5F)
 3873
 3677
 18144
 17955
 


Thus, by examining the release build results for the device, it can be concluded that on the current generation of devices it is most efficient to use casting in C# and Convert.ToInt32 in

本文作者:佚名 来源:www.weste.net
CIO之家 www.ciozj.com 微信公众号:imciow
   
免责声明:本站转载此文章旨在分享信息,不代表对其内容的完全认同。文章来源已尽可能注明,若涉及版权问题,请及时与我们联系,我们将积极配合处理。同时,我们无法对文章内容的真实性、准确性及完整性进行完全保证,对于因文章内容而产生的任何后果,本账号不承担法律责任。转载仅出于传播目的,读者应自行对内容进行核实与判断。请谨慎参考文章信息,一切责任由读者自行承担。
延伸阅读