Before coding, understand the format requirements:
Examples:
12345678
, 12345678.12
, 12345678.1234
12345678.12345
, 123456789
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>
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';
}
});
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';
}
});
12345678
, 12345678.1
, 12345678.1234
, and invalid inputs like 12345678.12345
.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.
Subscribe to the Email Newsletter