Charindu Edirisuriya Charindu Edirisuriya - 2 months ago 19x
ASP.NET (C#) Question

How to Format TextBox While Typing?

When the user types in the textbox i want it to format itself with decimals.

For example, if the user types

I want it to show up like
while he types it.


That problem proved to be more challenging than I expected (I should have known better). Here is what I got, using vanilla Javascript.

You can set event handler for the onkeyup event of the TextBox:

<asp:TextBox ID="txtAutoFormat" runat="server" onkeyup="processKeyUp(this, event)" />

And here is the Javascript code:

<script type="text/javascript">

    function extractDigits(str) {
        return str.replace(/\D/g, '');

    function findDigitPosition(str, index) {
        var pos = 0;
        for (var i = 0; i < str.length; i++) {
            if (/\d/.test(str[i])) {
                pos += 1;
                if (pos == index) {
                    return i + 1;

    function isCharacterKey(keyCode) {
        // Exclude arrow keys that move the caret
        return !(35 <= keyCode && keyCode <= 40);

    function processKeyUp(txt, e) {
        if (isCharacterKey(e.keyCode)) {
            var value = txt.value;

            // Save the selected text range
            var start = txt.selectionStart;
            var end = txt.selectionEnd;
            var startDigit = extractDigits(value.substring(0, start)).length;
            var endDigit = extractDigits(value.substring(0, end)).length;

            // Insert the thousand separators
            txt.value = extractDigits(value).replace(/(\d{1,3}|\G\d{3})(?=(?:\d{3})+(?!\d))/g, "$1,");

            // Restore the adjusted selected text range 
            txt.setSelectionRange(findDigitPosition(txt.value, startDigit), findDigitPosition(txt.value, endDigit));


CMS's solution to extract digits from string in Regex using javascript to return just numbers.

Alan Moore's regular expression to insert thousand separators in How do I add thousand separators with reg ex?.

Note: Ron Royston's idea of using toLocaleString is also very interesting. It could provide a more universal solution. You could replace this line of processKeyUp:

txt.value = extractDigits(value).replace(/(\d{1,3}|\G\d{3})(?=(?:\d{3})+(?!\d))/g, "$1,");

with the following:

txt.value = Number(extractNumber(value)).toLocaleString();