Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Decimal to Integer Conversion

1. ## 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.

• var myDec=3.5
var myInt=parseInt(myDec) //returns 3

any help?

• Thankyou, that is just what I am after.

• 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

• 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.

•

#### Posting Permissions

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