简体   繁体   中英

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 . And want to convert it to an int , this is what I can do:

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.

Disregarding the "fastest" question - use 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) . 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/

On a side-note Round has different behavior from Truncate .

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.

EDIT: Also be careful of overflowing on the cast!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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