Convert Floating Point numbers to integer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Bhavs
    New Member
    • Sep 2008
    • 16

    Convert Floating Point numbers to integer

    Hi...

    Can anyone help me with the code to convert 4E+07 to 40,000,000 in c#

    Thanks,
    Bh...
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    If the number is already in a float or double datatype, just type cast it down to an int.

    EDIT:
    After seeing the example below, I suppose I should provide one too
    [code=c#]

    //Need to append F to store it in a float percision
    float myfloat = 4E+07F;
    //or you could store it as a double
    double mydouble=4E+07;

    int myint=(int)myfl oat;
    //or
    int myint=(int)mydo uble;

    [/code]

    Comment

    • Bassem
      Contributor
      • Dec 2008
      • 344

      #3
      Hello Bhavs,

      Type Casting like Plater said,

      float x = 12.8;
      int n = (int) x;
      or
      int n = ConvertToInt32( x);

      Comment

      • uogen
        New Member
        • Jan 2009
        • 18

        #4
        HI ,Bassem
        why you use 12.8?
        represent what?

        Comment

        • Bassem
          Contributor
          • Dec 2008
          • 344

          #5
          Hello uogen
          It represents nothing except a floating point number, any number i meant. So, you can convert a float number to integer by truncate the fraction.

          Regards,
          Bassem

          Comment

          • r035198x
            MVP
            • Sep 2006
            • 13225

            #6
            Of course the solutions given are correct only if the floating point number is less than the largest int.

            Comment

            • Bassem
              Contributor
              • Dec 2008
              • 344

              #7
              Sure, r035198x. Otherwise we may use long int64.

              Comment

              • r035198x
                MVP
                • Sep 2006
                • 13225

                #8
                Originally posted by Bassem
                Sure, r035198x. Otherwise we may use long int64.
                Which also has a maximum value ...

                Comment

                Working...