The Number object's toFixed() method
The toFixed()
method formats a number using fixed-point notation, returning a string representation with a specified number of digits after the decimal point.
Prerequisites
This tutorial assumes that you're familiar with:
SyntaxnumObj.toFixed([digits])
Parametersdigits (optional):
Number of digits to appear after the decimal point
Must be between 0 and 20 (inclusive), browser implementations may support larger values
Default is 0 if not specified
If the value is too large or is a negative number, a RangeError is thrown
Return value
numObj.toFixed([digits])
digits (optional):
Number of digits to appear after the decimal point
Must be between 0 and 20 (inclusive), browser implementations may support larger values
Default is 0 if not specified
If the value is too large or is a negative number, a RangeError is thrown
The toFixed()
method returns a string representation of the number with exactly the specified number of digits after the decimal point. The number is rounded if necessary, and zeros are added if needed to achieve the correct length.
ExamplesExample 1: Basic number formatting
In the code below, the function toFixedEx1()
demonstrates basic number formatting with toFixed()
.
function toFixedEx1() {
let num = 42.1234;
// Varying decimal places
Logger.log(num.toFixed(0)); // "42" (rounded, no decimal places)
Logger.log(num.toFixed(1)); // "42.1" (rounded to 1 decimal place)
Logger.log(num.toFixed(2)); // "42.12" (rounded to 2 decimal places)
Logger.log(num.toFixed(3)); // "42.123" (rounded to 3 decimal places)
Logger.log(num.toFixed(6)); // "42.123400" (padded with zeros to 6 decimal places)
// Integer values
let intNum = 42;
Logger.log(intNum.toFixed(2)); // "42.00" (adds decimal places with zeros)
// Default behavior (0 decimal places)
Logger.log(num.toFixed()); // "42" (same as toFixed(0))
}
Output:
42
42.1
42.12
42.123
42.123400
42.00
42
Example 2: Rounding behavior
In the code below, the function toFixedEx2()
shows how toFixed()
handles rounding.
function toFixedEx2() {
// Rounding up
Logger.log((1.235).toFixed(2)); // "1.24" (rounds up)
// Rounding down
Logger.log((1.234).toFixed(2)); // "1.23" (rounds down)
// Rounding very small numbers
Logger.log((0.000001).toFixed(2)); // "0.00" (rounds to zero with 2 decimal places)
Logger.log((0.000001).toFixed(6)); // "0.000001" (shows actual value with 6 places)
// Rounding large numbers
Logger.log((1234.5678).toFixed(2)); // "1234.57"
}
Output:
1.24
1.23
0.00
0.000001
1234.57
Example 3: Handling special cases
In the code below, the function toFixedEx3()
demonstrates handling of special cases and edge cases.
function toFixedEx3() {
// Very large numbers
Logger.log((1e21).toFixed(2)); // "1e+21" (scientific notation preserved for very large numbers)
// Very small decimal places
Logger.log((0.1).toFixed(20)); // "0.10000000000000000555" (floating point precision issues revealed)
// Negative numbers
Logger.log((-1.23).toFixed(1)); // "-1.2"
// Zero
Logger.log((0).toFixed(4)); // "0.0000"
try {
// Invalid parameter (outside range)
Logger.log((123.45).toFixed(-1)); // Will throw RangeError
} catch(e) {
Logger.log("Error: " + e.message);
}
// Converting result back to number
let str = (1.23).toFixed(2); // "1.23"
let num = Number(str); // 1.23 (back to number)
Logger.log(typeof str); // "string"
Logger.log(typeof num); // "number"
}
Output:
1e+21
0.10000000000000000555
-1.2
0.0000
Error: digits argument must be between 0 and 100
string
number
Example 4: Financial calculations
In the code below, the function toFixedEx4()
demonstrates using toFixed()
for financial calculations.
function toFixedEx4() {
// Currency formatting
let price = 19.99;
Logger.log("$" + price.toFixed(2)); // "$19.99"
// Calculate tax
let taxRate = 0.0725; // 7.25%
let tax = price * taxRate;
Logger.log("Tax: $" + tax.toFixed(2)); // "Tax: $1.45"
// Calculate total
let total = price + tax;
Logger.log("Total: $" + total.toFixed(2)); // "Total: $21.44"
// Calculating interest
let principal = 1000;
let rate = 0.05; // 5%
let interest = principal * rate;
Logger.log("Interest: $" + interest.toFixed(2)); // "Interest: $50.00"
// Formatting percentages
let percentValue = 0.1234;
Logger.log("Percentage: " + (percentValue * 100).toFixed(1) + "%"); // "Percentage: 12.3%"
}
Output:
$19.99
Tax: $1.45
Total: $21.44
Interest: $50.00
Percentage: 12.3%
Example 5: Working with spreadsheet data in Apps Script
In the code below, the function toFixedEx5()
demonstrates using toFixed()
with Google Sheets data.
function toFixedEx5() {
// This function is designed to be used in a Google Sheets script
// Simulate getting values from spreadsheet
let values = [1.2345, 5.6789, 10.5, 0.99, 123.456789];
// Format values to 2 decimal places
let formattedValues = values.map(function(value) {
return value.toFixed(2);
});
Logger.log("Original values: " + values.join(", "));
Logger.log("Formatted values: " + formattedValues.join(", "));
// Calculate average and format result
function calculateAverage(numbers) {
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
let avg = sum / numbers.length;
return avg.toFixed(2);
}
Logger.log("Average: " + calculateAverage(values));
}
Output:
Original values: 1.2345, 5.6789, 10.5, 0.99, 123.456789
Formatted values: 1.23, 5.68, 10.50, 0.99, 123.46
Average: 28.37
toFixed() vs. toPrecision() vs. toString()
Apps Script provides several methods for formatting numbers. Here's how they compare:
function compareNumberFormattingMethods() {
let num = 12.3456789;
// toFixed: formats to specific decimal places
Logger.log(num.toFixed(2)); // "12.35" (2 decimal places, rounded)
// toPrecision: formats to specific total digits (before and after decimal)
Logger.log(num.toPrecision(4)); // "12.35" (4 significant digits, rounded)
// toString: converts to string, optional parameter for different bases
Logger.log(num.toString()); // "12.3456789" (full precision)
// For larger numbers, the difference becomes more apparent
let largeNum = 1234.56789;
Logger.log(largeNum.toFixed(2)); // "1234.57" (2 decimal places)
Logger.log(largeNum.toPrecision(4)); // "1235" (4 significant digits)
Logger.log(largeNum.toString()); // "1234.56789" (full precision)
}
Output:
12.35
12.35
12.3456789
1234.57
1235
1234.56789
Common Pitfall: Return value is a string
Remember that toFixed()
returns a string, not a number:
function stringReturnValue() {
let num = 5.123;
let formatted = num.toFixed(2); // "5.12"
Logger.log(typeof formatted); // "string"
// This works because of JavaScript's automatic type conversion
Logger.log(formatted * 2); // 10.24
// But this concatenates rather than adds
Logger.log(formatted + 5); // "5.125" (string concatenation)
// Convert back to number when needed
Logger.log(Number(formatted) + 5); // 10.120000000000001 (numeric addition; floating-point precision issues revealed)
}
Common Use Cases
The toFixed()
method is useful in many scenarios when working with Google Apps Script:
Data presentation: Ensuring consistent decimal precision in reports and spreadsheets.
User interface: Displaying numeric values with appropriate precision.
Percentage formatting: Converting decimal values to percentage representation.
Scientific measurements: Formatting values with discipline-specific precision requirements.
Spreadsheet automation: Generating formatted reports from raw data.
Best Practices
When using the toFixed()
method, keep these tips in mind:
Remember that
toFixed()
returns a string.Use
toFixed()
primarily for display formatting, not for fixing floating-point precision issues in calculations.For internationalization concerns (different decimal separators), combine
toFixed()
with additional formatting or consider usingIntl.NumberFormat
.
Conclusion
In this tutorial, you learned how to use the toFixed()
method to format numbers with specific decimal precision in Google Apps Script. You can use toFixed()
to ensure your numeric data is presented consistently and professionally in your Apps Script projects.
Small Scripts, Big Impact
Join 1,500+ professionals who are supercharging their productivity with Google Sheets automation
By subscribing, you agree to our Privacy Policy and Terms of Service