Tiger
Tiger

Reputation: 47

Limit numbers after decimal, add 0 if one digit

I'm trying to make a text field so that if there's a number 153.254, that becomes 153.25. And if the field contains 154.2, an extra 0 is added to fill two spots after decimal; 154.20.

toFixed() works great but I don't want the number rounded. Also came across other solutions where if I'm typing in 1.40, then if I move the cursor back after 1, I can't type anything in unless I clear the field and start over.

Is there a simple jQuery way to limit two characters after a decimal, and then if there's only one character after the decimal, add a zero to fill the two character limit? (The field may receive value from database that's why the second part is required)

Solution Update: For those interested, I put this together to achieve what I wanted (Thanks to answers below and also other questions here on stackoverflow)

           $('.number').each(function(){
                         this.value = parseFloat(this.value).toFixed(3).slice(0, -1);
                    });
           $('.number').keyup(function(){
                        if($(this).val().indexOf('.')!=-1){         
                            if($(this).val().split(".")[1].length > 2){                
                                if( isNaN( parseFloat( this.value ) ) ) return;
                                this.value = parseFloat(this.value).toFixed(3).slice(0, -1);

                            }  
                         }            
                         return this; //for chaining
                    });

Upvotes: 2

Views: 3431

Answers (3)

Noitidart
Noitidart

Reputation: 37238

try this:

var num = 153.2

function wacky_round(number, places) {
    var h = number.toFixed(2);

    var r = number.toFixed(4) * 100;
    var r2 = Math.floor(r);
    var r3 = r2 / 100;
    var r4 = r3.toFixed(2);

    var hDiff = number - h;
    var r4Diff = number - r3;
    var obj = {};
    obj[hDiff] = h;
    obj[r4Diff] = r4;
    if (r4Diff < 0) {
        return h;
    }
    if (hDiff < 0) {
        return r4;
    }
    var ret = Math.min(hDiff, r4Diff);

    return obj[ret];
}

alert(wacky_round(num, 2))

Upvotes: 2

Johan
Johan

Reputation: 35194

How about

function doStuff(num){
    var n = Math.floor(num * 100) / 100,
        s = n.toString();

    // if it's one decimal place, add a trailing zero:
    return s.split('.')[1].length === 1 ? (s + '0') : n;
}

console.log(doStuff(1.1), doStuff(1.111)); // 1.10, 1.11

http://jsfiddle.net/NYnS8/

Upvotes: 1

jshanley
jshanley

Reputation: 9128

you could do myNumber.toFixed(3).slice(0, -1)

Upvotes: 6

Related Questions