Math.abs() - and two functions:
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; Math.abs(newVal); > 57.64
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:
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
var centerX = parseInt(centers, 10);
10 is the base, providing a value of
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%"; console.log(parseFloat(FP)); > 33.33333
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.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.