What are some useful built-in JavaScript functions for type conversion and math?
JavaScript ships with built-ins like parseInt/parseFloat for turning strings into numbers, the Math library for rounding and randomness, and toFixed for formatting decimals.
You don't have to write everything yourself — the language provides ready-made functions for common jobs. The most useful from the basics:
Turning text into numbers (the global functions). These read a number out of the front of a string and stop at the first non-numeric character:
| Function | Purpose | Example |
|---|---|---|
parseFloat(str) |
String → decimal number | parseFloat('3.14') → 3.14 |
parseInt(str) |
String → whole number | parseInt('42px') → 42 |
(If the string can't be read as a number at all, these return NaN.)
Math — the Math object groups mathematical helpers:
| Function | Purpose | Example |
|---|---|---|
Math.floor(x) |
Round down to a whole number | Math.floor(3.7) → 3 |
Math.round(x) |
Round to the nearest whole number | Math.round(3.5) → 4 |
Math.random() |
A random number between 0 and 1 | Math.random() → 0.472... |
Number formatting:
| Method | Purpose | Example |
|---|---|---|
toFixed(n) |
Format with n decimal places (returns a string) |
(3.14159).toFixed(2) → '3.14' |
A gotcha worth remembering: toFixed gives back a string, not a number — handy for display, but don't do further math on the result without converting it back.