Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New to the CF scene
    Join Date
    May 2003
    Location
    New Zealand
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Decimal to Integer Conversion

    How can I convert a decimal to an integer. For example in other languages I could use
    x=int(y/z)
    in this iinstance no matter what values y and z are ( apart from z=0) x would return an integer value.

    Is there an equivalent in javascript???

    Thanks.

  • #2
    Senior Coder Spudhead's Avatar
    Join Date
    Jun 2002
    Location
    London, UK
    Posts
    1,856
    Thanks
    8
    Thanked 110 Times in 109 Posts
    var myDec=3.5
    var myInt=parseInt(myDec) //returns 3

    any help?

  • #3
    New to the CF scene
    Join Date
    May 2003
    Location
    New Zealand
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thankyou, that is just what I am after.

  • #4
    Regular Coder
    Join Date
    Jun 2002
    Location
    Atlanta, GA.
    Posts
    313
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Just to complete this thread you may want to know about Math.floor(), Math.round() and Math.ceil()

    var float1 = 3.4;
    var float2 = 3.5;

    //Always round down
    Math.floor(float1); //returns 3
    Math.floor(float2); //returns 3

    //Round to the closest integer
    Math.round(float1); //returns 3
    Math.round(float2); //returns 4

    //Always round up
    Math.ceil(float1); //returns 4
    Math.ceil(float2); //returns 4

  • #5
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Yes, and I'll go one step further and add that the parseInt() function has a 2nd (optional) parameter, the radix of the input (parseInt() always returns a base-10 number)

    parseInt( 'A', 16 ); // returns 10
    parseInt( 100, 2 ); // returns 4

    If you leave off the radix argument, parseInt does it's best to determine the radix based on the input.

    parseInt( 3.5 ); // return 3 - base 10 assumed
    parseInt( 0xA ); // returns 10 - base 16 assumed
    parseInt( '011' ); // returns 9 - base 8 assumed

    This is a common pitfall when trying to extract an integer from a string.
    My Site | fValidate | My Brainbench | MSDN | Gecko | xBrowser DOM | PHP | Ars | PVP
    “Minds are like parachutes. They don't work unless they are open”
    “Maturity is simply knowing when to not be immature”


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •