Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best method to convert floating point to an integer in JavaScript?

There are several different methods for converting floating point numbers to Integers in JavaScript. My question is what method gives the best performance, is most compatible, or is considered the best practice?

Here are a few methods that I know of:

var a = 2.5; window.parseInt(a); // 2 Math.floor(a);      // 2 a | 0;              // 2 

I'm sure there are others out there. Suggestions?

like image 850
Mathew Byrne Avatar asked Sep 25 '08 03:09

Mathew Byrne


People also ask

How do you convert floating numbers to integers?

Method 1: Conversion using int(): To convert a float value to int we make use of the built-in int() function, this function trims the values after the decimal point and returns only the integer/whole number part. Example 1: Number of type float is converted to a result of type int.

Which method converts the string into a number in JavaScript integer or float both?

Javascript has provided a method called parseFloat() to convert a string into a floating point number.

Which method is used to convert integer data type to float?

The floatValue() function can convert a given integer value into float. It belongs to the java. lang. Integer class.

How do you convert a number to an integer in JavaScript?

In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.


2 Answers

According to this website:

parseInt is occasionally used as a means of turning a floating point number into an integer. It is very ill suited to that task because if its argument is of numeric type it will first be converted into a string and then parsed as a number...

For rounding numbers to integers one of Math.round, Math.ceil and Math.floor are preferable...

like image 115
Jason Bunting Avatar answered Sep 24 '22 03:09

Jason Bunting


Apparently double bitwise-not is the fastest way to floor a number:

var x = 2.5; console.log(~~x); // 2 

Used to be an article here, getting a 404 now though: http://james.padolsey.com/javascript/double-bitwise-not/

Google has it cached: http://74.125.155.132/search?q=cache:wpZnhsbJGt0J:james.padolsey.com/javascript/double-bitwise-not/+double+bitwise+not&cd=1&hl=en&ct=clnk&gl=us

But the Wayback Machine saves the day! http://web.archive.org/web/20100422040551/http://james.padolsey.com/javascript/double-bitwise-not/

like image 40
bcherry Avatar answered Sep 26 '22 03:09

bcherry