How to Format Numbers in JavaScript
Maksudur Rahman
Software Engineer
Step 1: Understanding the Task
Before coding, understand the format requirements:
Numbers should have exactly 8 digits before the decimal.
The decimal part is optional but can have 1 to 4 digits.
Examples:
Valid:
12345678,12345678.12,12345678.1234Invalid:
12345678.12345,123456789
Step 2: Create an Input Field
Start by creating an input field in your HTML where users can enter numbers:
<input
type="text"
id="numberInput"
placeholder="Enter 8 digits or 8.1234"
/>
<button id="formatButton">Format</button>
<p id="output"></p>
Step 3: Write JavaScript for Validation
Add validation to ensure the input meets the format requirements.
document.getElementById('formatButton').addEventListener('click', function () {
const input = document.getElementById('numberInput').value;
const output = document.getElementById('output');
const regex = /^\d{8}(\.\d{1,4})?$/;
if (regex.test(input)) {
output.textContent = `Valid format: ${input}`;
output.style.color = 'green';
} else {
output.textContent = 'Invalid format. Please enter 8 digits or 8 digits with up to 4 decimals.';
output.style.color = 'red';
}
});
Step 4: Format the Input
If the input is valid, you can format it to always display as 12345678.1234:
function formatToFixed(value) {
const [wholePart, decimalPart] = value.split('.');
const formattedDecimal = (decimalPart || '').padEnd(4, '0').slice(0, 4);
return `${wholePart}.${formattedDecimal}`;
}
document.getElementById('formatButton').addEventListener('click', function () {
const input = document.getElementById('numberInput').value;
const output = document.getElementById('output');
const regex = /^\d{8}(\.\d{1,4})?$/;
if (regex.test(input)) {
output.textContent = `Formatted number: ${formatToFixed(input)}`;
output.style.color = 'green';
} else {
output.textContent = 'Invalid format. Please enter 8 digits or 8 digits with up to 4 decimals.';
output.style.color = 'red';
}
});
Step 5: Testing
Test the input with various cases, such as
12345678,12345678.1,12345678.1234, and invalid inputs like12345678.12345.
Test Cases
Input
Valid
Reason
12345678
✅
Matches 8 digits.
12345678.12
✅
Matches 8 digits with 2 decimals.
12345678.1234
✅
Matches 8 digits with 4 decimals.
12345678.12345
❌
Decimal part exceeds 4 digits.
123456789
❌
More than 8 digits before the decimal.
1234567.12
❌
Less than 8 digits before the decimal.
.1234
❌
Missing 8 digits before the decimal.
This ensures strict adherence to the specified format while providing user-friendly validation.