Search code examples
javascriptactionscript-3

Formatting Price Input


ideally this is for AS3, but I can always convert it down from JavaScript. Basically I want type numbers into a field and have it add the decimal. The issue is, the keyboard won't have a "." key

So if the final output was 10.45

it would automatically start to format as I type:

1 it would change to .01. And as I keep typing.. .01
.10
10.40 10.45


Solution

  • This can be accomplished by some simple string manipulation. Just split the string into parts and insert the decimal.

    HTML

    <input type="text" id="price" onchange="formatPrice(this)" />
    

    Javascript

    function formatPrice(obj) {
        //remove any existing decimal
        p = obj.value.replace('.','');
    
        //get everything except the last 2 digits
        var l = p.substring(-2, p.length-2);
    
        //get the last 2 digits
        var r = p.substring(p.length-2,p.length);
    
        //update the value
        obj.value = l + '.' + r;
    }
    

    You can see it working here: https://jsfiddle.net/x3wey5uk/