Overview
In web applications that handle measurement or financial data, displaying raw numbers can result in too many digits or inconsistent formatting, which reduces readability.
This article explains how to use standard JavaScript methods to fix decimal places or specify significant figures. We will demonstrate these techniques by implementing a dashboard that formats real-time sensor values for a monitor system.
Specifications (Input/Output)
Comparing toFixed and toPrecision
| Method | Meaning | Return Type | Primary Use Case |
toFixed(n) | Fixes decimal places to n digits | String | Currency, percentages, general measurements |
toPrecision(n) | Sets significant figures to n digits | String | Scientific calculations, displaying very large or small numbers |
- Input: Target numeric value (Number type).
- Output: Formatted text (String type).
- If the number of digits is less than specified, it is padded with zeros.
- If the number of digits exceeds the limit, the value is rounded.
Basic Usage
The following snippets demonstrate the behavior of each method.
1. Fixing Decimal Places (toFixed)
Use this when you want to unify the length of the decimal part, such as for currency or standard measurement data.
const pi = 3.14159;
console.log(pi.toFixed(2)); // "3.14"
const preciseVal = 123.4567;
console.log(preciseVal.toFixed(1)); // "123.5" (rounded)
const integerVal = 10;
console.log(integerVal.toFixed(2)); // "10.00" (zero-padded)
2. Specifying Significant Figures (toPrecision)
This sets the total number of significant digits (integer part + decimal part).
const weight = 0.0012345;
console.log(weight.toPrecision(2)); // "0.0012"
const distance = 12345.6789;
console.log(distance.toPrecision(3)); // "1.23e+4" (may use exponential notation)
const score = 4.56;
console.log(score.toPrecision(2)); // "4.6" (rounded)
console.log(score.toPrecision(4)); // "4.560" (zero-padded)
Full Code (HTML / JavaScript)
This demo simulates a factory sensor monitoring system. Different data types—CPU Temperature (fixed decimals) and Pressure Coefficient (significant figures)—are generated and formatted in real-time.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sensor Monitor Demo</title>
<style>
.monitor-panel {
font-family: 'Courier New', monospace;
background: #222;
color: #0f0;
padding: 20px;
border-radius: 8px;
width: 300px;
}
.data-row {
display: flex;
justify-content: space-between;
margin-bottom: 10px;
border-bottom: 1px solid #444;
padding-bottom: 5px;
}
.label { color: #888; }
.value { font-weight: bold; font-size: 1.2em; }
</style>
</head>
<body>
<div class="monitor-panel">
<h3>System Status</h3>
<div class="data-row">
<span class="label">CPU Temp:</span>
<span id="temp-display" class="value">--.--</span>
</div>
<div class="data-row">
<span class="label">Pressure:</span>
<span id="pressure-display" class="value">--</span>
</div>
</div>
<script src="monitor.js"></script>
</body>
</html>
JavaScript
/**
* Class to simulate sensor data and update the display
*/
class SensorMonitor {
constructor() {
this.tempElement = document.getElementById('temp-display');
this.pressureElement = document.getElementById('pressure-display');
this.isRunning = false;
}
/**
* Start monitoring
*/
start() {
this.isRunning = true;
this.updateLoop();
}
/**
* Update loop
* Uses requestAnimationFrame for smooth updates
*/
updateLoop() {
if (!this.isRunning) return;
// Get current virtual sensor values and update display
this.render();
// Re-execute on the next frame
requestAnimationFrame(() => this.updateLoop());
}
/**
* Generate data and update the DOM
*/
render() {
// Generate pseudo-fluctuation values from current time (using sine waves)
const now = Date.now();
// Scenario 1: CPU Temperature (fluctuates between 30 and 70 degrees)
// Format to 2 decimal places -> toFixed(2)
const rawTemp = 50 + Math.sin(now / 2000) * 20;
this.tempElement.textContent = `${rawTemp.toFixed(2)} Celsius`;
// Scenario 2: Fine pressure fluctuation coefficient (precise values around 0.001 to 0.005)
// Track trends using 3 significant figures -> toPrecision(3)
const rawPressure = 0.003 + Math.cos(now / 500) * 0.002;
this.pressureElement.textContent = `${rawPressure.toPrecision(3)} hPa`;
}
}
// Instantiate and start monitoring
const monitor = new SensorMonitor();
monitor.start();
Customization Tips
- Adjusting Update Frequency:
requestAnimationFrameruns at the monitor’s refresh rate (usually 60fps). If the numbers change too fast to read, usesetTimeoutorsetIntervalto throttle updates to once per second. - Applying Locales: When displaying currency like Yen or Dollars, consider using
Intl.NumberFormatinstead oftoFixed. This automates comma separation and currency symbols. - Avoiding Exponential Notation:
toPrecisionmay return values like1.23e+5depending on the digit count. If this is not user-friendly, add logic to switch totoFixedfor larger numbers.
Important Notes
The Return Value is a String
Both
toFixedandtoPrecisionreturn aStringtype. Performing further calculations with these results can lead to bugs where numbers are concatenated as strings (e.g.,"10.00" + 5 = "10.005"). Complete all calculations first and use these methods only for final display.
Rounding Precision Issues
Due to the nature of floating-point numbers in JavaScript (IEEE 754), rounding may not always behave as expected (e.g.,
(1.005).toFixed(2)might result in"1.00"). For financial systems requiring strict rounding, consider using dedicated libraries like Decimal.js.
Advanced Applications
Progress Bar Percentage Display
When displaying progress for tasks like file uploads, toFixed(0) is useful if only integer values are required.
// Simulation of upload progress
function formatProgress(loaded, total) {
if (total === 0) return '0%';
const percent = (loaded / total) * 100;
// Discard decimal places and convert to an integer string
return `${percent.toFixed(0)}%`;
}
console.log(formatProgress(345, 1000)); // "35%"
Conclusion
The toFixed method is ideal for fixed-point notation, such as unifying currency or UI values, while toPrecision is better suited for scientific measurements where significant figures are critical. Understanding that both return strings and separating calculation logic from display logic are the keys to preventing bugs. Additionally, while DOM updates per animation frame are smooth, optimizing updates to occur only when data changes can result in more refined code for large-scale applications.
