...

Decimal to Integer Conversion

seriousfun
07-03-2003, 11:10 AM
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.

07-03-2003, 01:00 PM
var myDec=3.5
var myInt=parseInt(myDec) //returns 3

any help?

seriousfun
07-03-2003, 02:12 PM
Thankyou, that is just what I am after.

RoyW
07-03-2003, 06:49 PM
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

beetle
07-03-2003, 07:12 PM
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.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum