开发者

Convert.ToInt or String.Split : which is more efficient?

Which way开发者_开发技巧 is better for removing float decimals places or is there a more efficient way?

Rounding is not important, i am interested in displaying the number

      Float number;            
      1- int wholeNumber= Convert.ToInt(number);
         string display=wholeNumber.ToString();

      2- string [] splitNumber= number.ToString().Split('.');
         string display=splitNumber[0];


Here are two oprions that are more efficient:

Simply cast the number instead of calling Convert.ToInt32:

((int)number).ToString()

Format the number using a format specifier with zero decimals:

number.ToString("N0")

The first one should be slightly faster, as it's easier to format an integer than an floating point number.

If you want something that really is efficient, you would cast the number to integer, then format it into a string yourself using code that is optimised to do only what you need and nothing more.


Since you are just dropping the decimal, do:

int wholeNumber = (int)number;

That will effectively drop the decimal. Note that it will not round the number, but that is not the behavior that you requested.


1 is better, because it describes what you're doing. 2 breaks in different locales.


int i = (int)number;
string display = i.ToString();

The cast to int will automatically drop any decimal places


I'm assuming that by more efficient, you mean "faster".

Have you tried to determine this yourself? I doubt you'll get a definitive answer unless someone else goeas ahead and tries it.

Set up a loop doing the same process 1000 times or so (adjust the number as you see fit) and then time the difference.


Using number.ToString("N0") is a slam-dunk. Trying to optimize it is pointless, whatever you are doing to display the string to the user is going to be a lot more expensive.


If it's just for display, pass in the correct format string, and you don't need to convert at all:

Float number;             
string display=number.ToString("F0"); 

Note: this is efficient coding, not necessarily memory or speed efficiency - you'll only be able to determine that through timing of many repeated loops over each method.


This test passes so both work. Not sure about the efficiency though. Which do you think reads better? The Truncate call is more explicit as to what you're doing.

[Test]
public void Getting_whole_number()
{
   Assert.AreEqual("5", Math.Truncate(5.5).ToString());
   Assert.AreEqual("5", ((int)5.5).ToString());
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜