views:

102

answers:

8

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];
+4  A: 

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.

Kevin Crowell
+3  A: 

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

Jimmy
+1  A: 
int i = (int)number;
string display = i.ToString();

The cast to int will automatically drop any decimal places

thecoop
+1  A: 

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.

David Stratton
+4  A: 

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.

Guffa
+1 for `number.ToString("N0")`, which is simple and exactly describes the code's intention, making it easy to read. I doubt any inefficiency it possesses will be an issue in most situations.
Brian
+1  A: 

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.

jball
+1  A: 

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());
}
Rob
+1  A: 

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.

Hans Passant