The toFixed()
function in JavaScript is a method of the Number prototype. It formats a number using fixed-point notation, returning the result as a string. The function accepts one argument: the number of digits to appear after the decimal point.
let num = 5.56789;
let n = num.toFixed(2); // "5.57"
In the above example, the toFixed()
function rounds the number to two decimal places. Remember, toFixed()
will always round the number and not truncate it.
You can read more about multiple ways to round a number to n decimal places in javascript.
When to Use the toFixed() Function?
The toFixed()
function is particularly useful when you need to format numbers for display purposes. Here are a few scenarios where it might come in handy:
- Currency Formatting: When dealing with monetary values, it’s common to need a consistent number of decimal places, typically two. The
toFixed()
function makes this easy. - Scientific Calculations: For scientific or mathematical computations where precision matters, using
toFixed()
can help maintain a consistent level of precision. - Data Visualization: When presenting data in graphs or tables,
toFixed()
can help ensure numerical data is consistently formatted, making it easier for users to read and understand.
Example 1: Currency Formatting
let price = 15.3;
let formattedPrice = price.toFixed(2); // "15.30"
console.log('The price is $' + formattedPrice);
Example 2: Scientific Calculations
let pi = 3.141592653589793;
let shortPi = pi.toFixed(4); // "3.1416"
console.log('The value of Pi to four decimal places is ' + shortPi);
Example 3: Data Visualization
let data = [2.4567, 3.56789, 4.123456];
let formattedData = data.map(num => num.toFixed(2)); // ["2.46", "3.57", "4.12"]
console.log(formattedData);
Make .toFixed() return a number
While toFixed()
is a powerful function, it’s important to note that it returns a string, not a number. If you need to perform further mathematical operations on the result, you’ll need to convert it back to a number using Number()
, parseFloat()
, or the unary +
operator.
let num = 5.56789;
let n = num.toFixed(2); // "5.57"
let sum = Number(n) + 1; // 6.57