Skip to content

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.56 silently 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" and inputmode="decimal", always. An input you hand to Numora with type="number" becomes type="text".
  • spellcheck="false" and autocomplete="off", only when you did not set them. An input with autocomplete="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) * 100

Gives 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:

Numora: pasting 1.234,56

Read 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:

NumoraInput

Your 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:

  • keydown fires first. It reports the physical key, not the resulting character.
  • beforeinput fires once the browser has decided what the edit will be, but before it edits the DOM. It is cancelable. Numora formats here.
  • input fires 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.
  • keyup fires 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.

Backspace after a comma
With Numora

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:

  1. 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.
  2. It tells Numora what the edit is (inputType and data), so Numora can compute the intended value and the cursor position.
  3. It fires for keyboard, voice dictation, virtual keyboards and autocorrect, including cases where keydown never 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:

ValueTriggered byNumora action
insertTextTypingFormat and apply via setRangeText
deleteContentBackward / deleteContentForwardBackspace / DeleteRemove the selection, or the character before or after the cursor, then format and apply
deleteByCutCtrl/Cmd+XRemove the selection, then format and apply
deleteByDrag, word and line deletionsDragging text out, Ctrl/Alt+Backspace, Cmd+BackspaceRemove the selection, or everything before or after the cursor when nothing is selected, then format and apply
insertFromPasteCtrl/Cmd+VNever arrives. The paste handler cancels the paste first
historyUndo / historyRedoCtrl/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 calls preventDefault() and leaves the value alone.
  • handled: the caller calls preventDefault(), writes the formatted value with setRangeText, 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)
1. Read currentValue and selectionStart/End from the field,
   inputType and data from the event
2. insertText of a decimal key ('.', ',' or another keyboard's decimal mark)
     the value outside the selection already
     has a decimal separator,
     decimalMaxLength is 0, or
     the key is a non-ASCII mark that is the
     configured thousandSeparator        → { type: 'reject' }
     otherwise                           → convert to the configured separator
3. insertText of a digit after the decimal
   separator, past the decimal cap       → { type: 'reject' }
4. Compute intendedValue per inputType:
     insertText            → splice data over the selection
     deleteContentBackward → remove the selection, or the char before the cursor
     deleteContentForward  → remove the selection, or the char after the cursor
                             (both: when that char is the thousand separator,
                             also remove the digit beyond it)
     deleteByCut/Drag      → remove the selection
     word/line backward    → remove the selection, or everything before the cursor
     word/line forward     → remove the selection, or everything after the cursor
     anything else (drop, IME composition,
     undo, redo)                         → { type: 'skip' } (the browser continues)
5. insertText only: scientific notation in
   the result, allowScientificNotation off → { type: 'reject' }
6. insertText only: maxLength exceeded   → { type: 'reject' }
7. formatInputValue(intendedValue)       → sanitize → trim decimals →
                                           group (Change mode only)
     result equals the current value     → { type: 'reject' } (nothing to report)
8. isAllowed(raw) returns false          → { type: 'reject' }
9. Cursor: computeCaretFromEdit(...)     → rank of the sanitized text left of the
                                           cursor, found again in the formatted string
     formatting changed nothing          → the cursor the edit itself would leave
10. { type: 'handled', formatted, raw, cursorPos }

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:

Paste into the field

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:

  1. 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.
  2. It splices that text into the current value at the selection.
  3. It stops if the combined value holds scientific notation and allowScientificNotation is off.
  4. 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.
  5. It stops if isAllowed refuses the result, or if the result is what the field already shows. Otherwise it writes the result with setRangeText, places the cursor and calls your change callback with the raw value and the formatted value. No synthetic input event 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,56 pasted into a field with thousandSeparator="," is read as 1234.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'.

Wan grouping: 1234,5678

Groups of 4 from the right.

Grouping style

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.

The vanilla NumoraInput class passes both to onValueChange as { value, formattedValue }. On the instance, rawValue returns the raw value and formattedValue the formatted value:

import { NumoraInput } from 'numora'

new NumoraInput(container, {
  decimalMaxLength: 2,
  // onValueChange always receives both: the raw value and the formatted value.
  onValueChange: ({ value, formattedValue }) => console.log(value, formattedValue),
})

Type below. Both readouts update on every keystroke:

formattedValue
"1,234,567.89"
value
"1234567.89"