Formatting money with jquery

I wrote this little piece that was supposed to format the money, but for some reason it didn’t work. He constantly adds them every time ... any idea why there is a better way to do this.

$(".dollar").blur(function() {
    var curval = $(this).val(); 
    if ($(this).val().indexOf("$") != 0) {
        $(this).val("$" + $(this).val());
    } 
    if ($(this).val().indexOf(".") != 0){
        $(this).val($(this).val() + ".00");
    }
});
+3
source share
3 answers

I wrote another proof of dollar formatting that will take any number (1, 1,6, 2,52, 8,24272) and automatically format it before notation in dollars ($ 1.00, $ 1.60, $ 2.52, $ 8.24):

$('.dollars').blur(function(e){
    var curVal = parseFloat($(this).val()),
        curInt = parseInt(curVal, 10),
        curDec = parseInt(curVal*100, 10) - parseInt(curInt*100, 10);

    curDec = (curDec < 10) ? "0" + curDec : curDec;

    if (!isNaN(curInt) && !isNaN(curDec)) {
        $(this).val("$"+curInt+"."+curDec);
    }
});

See here in action.

+5
source

You can take a look at the jquery globalization plugin .

+3
source

indexOf . , , .

if ($(this).val().indexOf("$") < 0) {
    $(this).val("$" + $(this).val());
} 
if ($(this).val().indexOf(".") < 0){
    $(this).val($(this).val() + ".00");

oops — :-) , . - , , , , , .

+2

All Articles