[SalesForce] the best way to include commas(as thousand separator) as we are typing into a lightning input field

I have a lightning:input field like this

<lightning:input aura:id="field1" label="Amount"
                         name="amount" type="number"
                         disabled="{!v.isReadOnlyForm}"
                         required="true"
                         step="0.01"/>

Its a number field and users generally enters big numbers like millions.

Once numbers are entered and we focus out of the field commas are added as thousand separators.

But its hard for users to write big numbers . They need to count zeroes while typing. Is there any way to add commas while typing into the field ?

Best Answer

As Sunil has said, you can use one more label to display the updated value using the "onchange" event.

However, If you chose to add commas to the lightning input field itself, you won't be able to use type="number" as it will not allow ',' character. You can use type="text" and then add commas to the number in the onchange event.

<lightning:input aura:id="field1" 
                         label="Amount"
                         name="amount"
                         type="text"
                         disabled="{!v.isReadOnlyForm}"
                         required="true"
                         value = "{! v.price }"
                         step="0.01"
                         onchange="{!c.addCommas}"/>

then onchange event:

({
    addCommas : function(component, event, helper){
            let updatedPrice = component.get("v.price").replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            component.set("v.price", updatedPrice);
        }
})

The JavaScript part was explained in this answer.