简体   繁体   English

在C#中删除数字的分数值的最快方法

[英]Fastest way to remove fraction value of a number in C#

I know there are many ways to remove the fractional value of a number. 我知道有很多方法可以去除数字的小数。

For example, if I have a variable with the type of double and the number: 12.34 . 例如,如果我有一个类型为double且数字为12.34的变量。 And want to convert it to an int , this is what I can do: 想要将其转换为int ,这是我可以做的:

int var = (int)fractionalVar;
int var = (int)Math.Round(fractionalVar);
int var = (int)Math.Truncate(fractionalVar);

So my question: Which one is the fastest or is there a faster one? 所以我的问题是:哪一个是最快的?

EDIT: My fault, I don't mean to round anything. 编辑:我的错,我不是要四舍五入。 This is what I mean: Remove the fractional value from the number. 这就是我的意思:从数字中删除小数。 Example. 例。 12.34 to 12 AND ALSO 12.99 to 12. 12.34至12以及12.99至12。

Disregarding the "fastest" question - use Math.Truncate . 忽略“最快”问题-使用Math.Truncate Why? 为什么? Because your question is basically "which is the fastest way to truncate." 因为您的问题基本上是“这是截断最快的方法”。 That's irrelevant. 没关系 They are all very fast and O(1) . 它们都非常快,并且O(1) Use the cleanest one. 使用最干净的一个。 The one that's called like the action you actually want to perform. 类似于您实际要执行的操作。

Also read this: https://blog.codinghorror.com/micro-optimization-and-meatballs/ 另请阅读: https : //blog.codinghorror.com/micro-optimization-and-meatballs/

On a side-note Round has different behavior from Truncate . 在旁注中, RoundTruncate具有不同的行为。

Since all three methods cast a double, the two that call functions will be slower since there is more work to do. 由于这三个方法都转换为双精度,因此调用函数的两个方法将变慢,因为还有更多工作要做。 This can be confirmed with a benchmark. 这可以通过基准进行确认。

          Method |      N |      Mean |     Error |    StdDev |
---------------- |------- |----------:|----------:|----------:|
    BasicIntCast | 100000 | 0.0001 ns | 0.0002 ns | 0.0002 ns |
    RoundAndCast | 100000 | 0.0514 ns | 0.0064 ns | 0.0056 ns |
 TruncateAndCast | 100000 | 5.4704 ns | 0.0197 ns | 0.0165 ns |

As others have mentioned, your desired end result should determine which method you use. 正如其他人提到的那样,所需的最终结果应确定您使用哪种方法。 If you really want eg 12.999999... to become 12, then the cast to int will get the job done. 如果您真的希望例如12.999999 ...变为12,则将其强制转换为int即可完成工作。

EDIT: Also be careful of overflowing on the cast! 编辑:还请注意演员阵容上的溢出!

        double d = 12e25;
        int i = (int)d;
        Console.WriteLine(i);
        // -2147483648

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

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