Search code examples
javascriptangularinputnumber-formatting

Angular - Avoid scientific notation for [(ngModel)] number input field


In an application, I use an edit field to display and modify satoshi (example: 0.00000004).

This field is linked to the data model with a [(ngModel)]. the data type is a number.

Angular (or rather javascript or html) systematically translates it on loading in scientific notation: (example: 4e-8)

The type of field used "text" or "number" produces the same effect.

Is there a fancy way to force unscientific notation with a field bound to the data model and without changing the data model ?

Simple javascript example of the issue :

const elText = document.getElementById("satoshiText");
const elNumber = document.getElementById("satoshiNumber");
elText.value =0.00000001;
elNumber.value =0.00000001;
<input id="satoshiText" type="text" /><br /><br />
<input id="satoshiNumber" type="number" />


Solution

  • If you specify the value and event binding separately rather than using a two-way binding, you can add a pipe to format the number:

    <input [ngModel]="value | number:'1.8-8'" (ngModelChange)="value = $event">
    

    If you need this often, you could also write a custom form component whose ControlValueAccessor converts to the desired format.