A tiny, dependency-free JavaScript plugin that formats numbers in text inputs while you type (e.g. 1234567.5 → 1,234,567.5). It rejects non-numeric characters and can give you the raw number for form submission.
CDN
<script src="https://cdn.jsdelivr.net/gh/amiryxe/easy-number-separator@1.1.0/easy-number-separator.js"></script>Pinning a version (@1.1.0) is recommended. Use @latest for the newest release, or @master for the latest unreleased code.
Download: save easy-number-separator.js into your project and include it:
<script src="js/easy-number-separator.js"></script><input type="text" class="number-separator" />
<script>
easyNumberSeparator({ selector: '.number-separator' })
</script>| Option | Default | Description |
|---|---|---|
selector |
'.number-separator' |
CSS selector of the input(s) to format |
separator |
',' |
Thousands separator |
decimalSeparator |
'.' |
Decimal separator |
maxDecimals |
unlimited | Maximum decimal places (0 = no decimals) |
resultInput |
none | Selector of an input that receives the raw number (e.g. 1234567.5) |
submitRaw |
false |
Adds a hidden input with the input's name holding the raw number, so forms submit it unformatted |
disallowPaste |
false |
Block pasting into the input |
disallowDrop |
false |
Block dragging and dropping text into the input |
Custom separators
easyNumberSeparator({ selector: '.price', separator: '.', decimalSeparator: ',' }) // 1.234.567,89Limit decimals and get the raw value
<input type="text" class="price" />
<input type="hidden" id="price_raw" name="price" />easyNumberSeparator({ selector: '.price', maxDecimals: 2, resultInput: '#price_raw' })Submit raw values automatically
<form>
<input type="text" class="price" name="price" />
</form>easyNumberSeparator({ selector: '.price', submitRaw: true })The visible input stays formatted (its name moves to data-name), and a hidden <input name="price"> placed after it sends the raw number. Works for any number of inputs.
Several inputs, each with its own raw value
easyNumberSeparator({ selector: '#price', resultInput: '#price_raw' })
easyNumberSeparator({ selector: '#qty', resultInput: '#qty_raw' })Inputs added to the page later are picked up automatically.
Values set from code
Inputs that already have a value are formatted on start. If you change a value from code later (e.g. jQuery's .val()), call refresh():
const separator = easyNumberSeparator({ selector: '.price' })
$('.price').val(1500000)
separator.refresh() // 1,500,000Pasting
Pasted or dropped text is cleaned up by default ( $1,234 USD → 1,234). To block it instead:
easyNumberSeparator({ selector: '.price', disallowPaste: true, disallowDrop: true })Open index.html in a browser for the demo. Run the tests (Node 18+, no dependencies):
node --test test/