How a numeric input works
Numora is a plain text input with event listeners on it. When the user types or deletes, Numora steps in before the browser applies the edit. It works out the value the edit would produce, cleans it, formats it and writes it back with the cursor in the right place. Your code gets two strings: the raw value and the formatted value. The sections below go through that in order.
Why not <input type="number">
<input type="number"> arrived with HTML5 in 2014, and it does not suit money or token amounts:
- Locale-aware thousand separators are forbidden by spec.
- Pasting
1,234.56silently empties the field. - Increment arrows make no sense for currency or token amounts.
The 2017 addition of inputmode="decimal" fixed mobile keyboards but not formatting. Numora fills that gap.
So every Numora input is a real <input type="text">. There is no contenteditable div, no shadow DOM and no virtual cursor. Numora listens to events on this element and writes back to it, using the input's own value, selectionStart / selectionEnd, setRangeText and inputMode.
Numora sets four attributes on the input:
type="text"andinputmode="decimal", always. An input you hand to Numora withtype="number"becomestype="text".spellcheck="false"andautocomplete="off", only when you did not set them. An input withautocomplete="cc-number"keeps it.
Numora sets no pattern attribute, so native constraint validation never rejects a value the field itself produced. Add your own if you need one.
Why Number is the wrong type
JavaScript stores every number as a 64-bit IEEE 754 float. Most decimals you use in a financial UI, such as prices, ratios and percentages, have no exact binary representation. Do arithmetic on them and the error shows:
Number(value) * 100Gives 1998.9999999999998, not 1999
On a price field, 0.30000000000000004 is not the number the user meant. Numora has one rule here. Every value in the input is a string. Numora never converts it to a Number. The digits the user typed are the digits your code reads back.
What users actually type
The usual fix is <input type="text"> plus a regex like value.replace(/[^0-9.]/g, ''). It removes letters and currency symbols, and it silently corrupts everything else:
1.234,56Read as German format
A character-class regex cannot tell that 1.5e-7 is a number or that German 1.234,56 is about a thousand times larger than 1.23456. Numora reads a pasted value whole, so it expands scientific notation and checks for another locale's format first. Typed text is read one key at a time, with the separators you configured.
Plain <input> vs Numora
Paste messy text such as $1,234.56abc into a plain input and it stays as it is. Your code gets that string. Numora cleans and groups the value, so your code gets a string that parses as a number:
NumoraInputYour code gets "1234.56"
Typed one key at a time, the same text reads differently, because a typed , is a decimal key and b is the billion suffix.
The event pipeline
One keystroke fires four events on a focused <input>, always in the same order. The browser edits the DOM between the second and the third:
keydownfires first. It reports the physical key, not the resulting character.beforeinputfires once the browser has decided what the edit will be, but before it edits the DOM. It is cancelable. Numora formats here.inputfires after the value has changed and cannot be canceled. Numora uses it as a fallback. It reformats what the browser changed on its own, such as autofill, drop, IME commits, undo and redo. If the new value is not allowed, it puts the previous one back.keyupfires when the key is released. Numora ignores it.
In a Numora field, typing stops at beforeinput. Numora cancels the edit and writes the formatted value itself, so the browser never edits the DOM and input never fires:
Key up. Numora ignores it
keydown stays out of the way
Many input-mask libraries format in keydown. Numora's handler does one thing:
It moves the cursor over a thousand separator on Backspace and Delete. It deletes nothing. It acts only when three things hold: formatOn is 'change', so the separators are on screen while the user edits; a thousand separator is set; and no text is selected. With the cursor just after the comma in 1,234 (1,|234), keydown moves the cursor to the left of the comma. beforeinput then deletes the digit 1, not the comma, and the field shows 234.
beforeinput then deletes the 1.
Android soft keyboards often send keydown with the key Unidentified, or no keydown at all. So beforeinput has its own path: when a delete arrives with the cursor still next to a thousand separator, it deletes the digit on the far side of the separator. The result is the same 234.
Everything else, including decimal separators and character insertion, happens in beforeinput.
Why beforeinput
Formatting from keydown breaks IME input and accessibility tools. Numora formats from beforeinput instead, for three reasons:
- It fires before the browser edits the field and is cancelable, so only the formatted text is ever shown. There is no flash of unformatted text.
- It tells Numora what the edit is (
inputTypeanddata), so Numora can compute the intended value and the cursor position. - It fires for keyboard, voice dictation, virtual keyboards and autocorrect, including cases where
keydownnever fires.
It also fires for drag-and-drop and IME text. Numora lets the browser insert those and reformats the field on the input event that follows.
What Numora does depends on the inputType:
| Value | Triggered by | Numora action |
|---|---|---|
insertText | Typing | Format and apply via setRangeText |
deleteContentBackward / deleteContentForward | Backspace / Delete | Remove the selection, or the character before or after the cursor, then format and apply |
deleteByCut | Ctrl/Cmd+X | Remove the selection, then format and apply |
deleteByDrag, word and line deletions | Dragging text out, Ctrl/Alt+Backspace, Cmd+Backspace | Remove the selection, or everything before or after the cursor when nothing is selected, then format and apply |
insertFromPaste | Ctrl/Cmd+V | Never arrives. The paste handler cancels the paste first |
historyUndo / historyRedo | Ctrl/Cmd+Z / Ctrl+Y (Cmd+Shift+Z) | Pass through. Numora's own writes are not in the browser's undo history. The input fallback reformats whatever the browser changes |
The handler reads the field and the event but never writes to them. It returns one of three results, and the caller applies it:
skip: the caller does nothing and the browser continues.reject: the caller callspreventDefault()and leaves the value alone.handled: the caller callspreventDefault(), writes the formatted value withsetRangeText, places the cursor and reports the change.
setRangeText fires no input event. Your change callback gets both strings, as Raw value vs formatted value shows.
The handler's full decision order (handleOnBeforeInputNumoraInput)
Focus and blur
The formatOn option decides when thousand separators appear. With 'change', the default, Numora groups the value on every edit. With 'blur', the separators show only while the field is not focused. The rest of this page calls that blur mode.
In blur mode, focusing the field removes the separators and keeps the cursor on the same digit. On a mouse click the browser places the cursor after focus fires, so Numora waits for the click event before it removes them. The raw value stays the same, so only onFormattedValueChange is called.
Leaving the field settles the value in both modes. Numora puts the separators back, drops a trailing decimal separator, pads the decimals up to decimalMinLength, turns a negative zero such as -0 into 0 and empties a field that holds only a sign or a separator. Your change callback is called only if the raw value changed.
The sanitization pipeline
Every value Numora touches, whether typed, pasted or written from code, passes through the same ten steps in the same order. Each step is a pure function with one job. Three run only when their option is set: step 4 needs allowCompactNotation, step 9 needs padLeadingZero and step 10 needs maxLength. The figure has all three on. Before step 1, Numora cuts the text at 10,000 characters.
Watch three messy values go through it. Each step marks what it is about to change. Steps with nothing to do are skipped:
"$.75" goes through ten steps in order. 2 of them change it. The result is "0.75".
The figure reads its text with the field's own separators. A paste first checks the clipboard text for another locale's format. Step 3 also turns the minus variants U+2212, U+FF0D and U+FE63 into - and a native decimal mark such as ٫ into the field's decimal separator. A default field turns $.75 into .75, because padLeadingZero is off.
Paste messy text
Pick a messy value. It is pasted into the field, over whatever the field holds:
When the user pastes, the paste event fires first, and it carries the full ClipboardData object. Numora handles the paste there and cancels the event, so the browser never sends a beforeinput with inputType: 'insertFromPaste' for it.
The paste handler then does five things:
- It reads the clipboard's plain text, works out what each separator in it means (the rules are below) and rewrites the text with the field's own separators. A read-only or disabled field takes nothing.
- It splices that text into the current value at the selection.
- It stops if the combined value holds scientific notation and
allowScientificNotationis off. - It runs the combined value through the full pipeline. Thousand separators are always removed, because the clipboard text and the current value can both carry them.
- It stops if
isAllowedrefuses the result, or if the result is what the field already shows. Otherwise it writes the result withsetRangeText, places the cursor and calls your change callback with the raw value and the formatted value. No syntheticinputevent is dispatched.
Pasted text may come from another locale, so Numora does not assume the field's own separators. It decides what each . and , means:
- Both appear. The last one is the decimal mark and the rest is grouping. A German
1.234,56pasted into a field withthousandSeparator=","is read as1234.56. - One mark repeats. It is grouping.
- One mark appears once. It is the decimal mark when it is the field's own decimal separator. Otherwise it is grouping when the digits around it form valid groups (
1,234), and the decimal mark when they do not.
Dropped and autofilled text is read the same way, except in a focused field that formats on change, which reads it as text in its own format.
A paste is inserted into the text already there, at the selection. The demo selects the whole field first, so each value starts clean.
Thousand grouping styles
Regions group large numbers differently. Numora has three grouping styles, plus 'none'.
Groups of 4 from the right.
Cursor preservation
Input masks tend to get this wrong. A user clicks into the middle of 1,234,567 and types a digit. The formatter rebuilds the string with the commas in new places, and the cursor ends up several characters from where it should be.
Numora keeps the cursor between the same two digits however the separators move around it:
Naive formatter
NumoraInput
The 9 lands at the end in naive. Numora puts it after the 8.
Numora takes the text left of the edit, plus the inserted text, and runs it through the same pipeline as the whole value: separators removed, leading zeros dropped, notation expanded, decimals trimmed. The result is the text that belongs before the cursor. Numora then walks the final display string and matches that text character by character, skipping the thousand separators it added. It puts the cursor where the match ends.
Sometimes nothing matches, because the edit made Numora read the whole value again. Pasting e- into 1|5 gives 0.00001, and no character left of the cursor survives. The cursor then goes to the end of the text.
A paste whose tail was trimmed leaves the cursor after the last pasted character that survived. The grouping style only changes where the separators sit, so 'thousand', 'lakh' and 'wan' need no per-style code.
Raw value vs formatted value
Every formatting cycle produces two strings: the formatted value ("1,234.56") and the raw value ("1234.56"). Your form, validator and API expect the raw value. The user sees the formatted value.
In Numora React, both are exposed on the change event's target. e.target.value returns the raw value via a Proxy; e.target.formattedValue is the formatted value. The same target also behaves as a real HTMLInputElement, so selectionStart and the other properties still work:
Type below. Both readouts update on every keystroke:
The Proxy on e.target
The target of a change event is a Proxy around the real HTMLInputElement. It does three things:
- A read of
target.valuereturns the raw string. Every other read goes to the element, includingselectionStartandname. So doesformattedValue, a getter that Numora React defines on the input when it mounts, next torawValueandsetValue. - A function it returns, such as
focus(), is bound to the real input. A native method called on a Proxy would throw. - A write is forwarded to the real input. Assigning
target.valuechanges the field, and a later read oftarget.valuestill returns the raw string.
The event object is built by hand. It is not a React synthetic event. Its nativeEvent is a new Event('change') that was never dispatched, its isTrusted is false, and preventDefault() and stopPropagation() do nothing.
The Proxy only wraps e.target on change events. A forwarded ref points at the real DOM element, so read ref.current.formattedValue there:
Why beforeinput bypasses React's synthetic event system
React's event system uses delegation. A single listener at the root container fires handlers during the bubbling phase. That works for most events, but not for beforeinput. React's onBeforeInput is not the native event. React synthesizes it from textInput, keypress and composition events, so it cannot reliably cancel the edit before the browser applies it.
Switching to React's onBeforeInput prop broke validation and sanitization, and any character could be typed. So Numora React registers the native listener itself.
It registers the listener once, at mount, on the element itself. The listener reads options through a ref that a layout effect keeps current, so a prop change never re-registers it:
Why onChange fires only once
The handler writes the formatted value with setRangeText and calls onChange itself. setRangeText dispatches no input event. The HTML spec says so, and Chrome and jsdom both follow it. Nothing reaches React's handleChange afterwards. handleChange only ever sees edits the browser makes itself, such as autofill, drop, IME commits, undo and redo.
defaultValue vs value
NumoraInput renders the underlying <input> with defaultValue, not value:
A controlled input (value=) makes React write input.value back whenever it differs from the prop. That undoes what setRangeText just wrote and breaks formatting. defaultValue sets the DOM value once at mount, so setRangeText is the only thing that changes it while the user types.
When you pass a value prop, or change an option, a layout effect compares the prop with the DOM as raw text. Both sides are sanitized first, so grouping does not count, and a half-typed 1. that the parent echoes back as 1. is equal. A different string for the same number counts as a change, such as 1 for 1. or 1.50 for 1.5.
If the two differ, or the options changed, the effect formats the prop and writes it with writeValue. That write does not call onChange, unless the new options change the raw value, as a smaller decimalMaxLength can.
This is also how a controlled field holds its value. An edit goes into the DOM first, and Numora calls onChange and onValueChange. It then renders the component again, even if the parent kept its state. The layout effect runs, sees that the DOM differs from value, and writes the field back before the browser paints. If the parent accepted the edit, the prop already matches and nothing is written.