A rendering of a white mathematical shape inside a scaffolding structure

Dealing with numbers in JavaScript can be tricky. Received values don’t always fall inside expected ranges; sometimes they’re negative when you expect positive results. Sometimes they’re not even cast as numbers. Dealing with these conditions, and converting strings into useful numerical results, often falls to s method - Math.abs() - and two functions: parseInt and parseFloat.


Math.abs() returns the absolute value of a number - i.e. the number as a positive - without otherwise altering its value. Useful when working with results that may be negative, but which you need to be positive. In the console:

var newVal = -57.64;

> 57.64


As I’ve previously discussed, JavaScript treats values like "15" as a string, not a number. Results of numbers-as-strings are common when parsing with JavaScript, or gaining values from an ill-prepared array. Results aren’t always this clean, either: receiving strings like “17px” is not uncommon. The issue is how to convert that into an actual value for use in calculations.

Into this role steps parseInt, an automatic “cleaner” function that converts text that contains numbers into logical numerical values. The text used in parseInt should always be paired with a radix: the base of the number that the text should be converted into. On most occasions this will be 10 (i.e. the base of the ordinary counting numbers you use every day), but not all browsers assume this, so it needs to be specified.

Returning to my earlier example of rotating an element to touch and mouse positions: I found the center of an element with code like this:

var elem = document.getElementById("elem1")
var centerPoint = window.getComputedStyle(elem).transformOrigin;

centerPoint might yield a result that looks like this:

75px 75px

We can split() the result on the space between the values:

var centers = centerPoint.split(" "),

…but that still leaves the px as part of each string. To clean that up, we’ll use parseInt():

var centerX = parseInt(centers[0], 10);

…where 10 is the base, providing a value of 75 as a pure number. This result can then be used in calculations in JavaScript.


parseFloat is the floating point equivalent of parseInt: it converts text into a number with decimal places. Again, it can be useful in parsing CSS and other tasks, especially when dealing with floating-point percentages:

var FP = "33.33333%";

> 33.33333


While parseInt() and parseFloat() are extremely useful and powerful functions with some degree of “intelligence”, it’s important to test a range of expected values against parsed results, to ensure they yield usable numbers.

Rendering by Mikael Hvidtfeldt Christensen, used under a Creative Commons Attribution 2.0 Generic license

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.