Limit numbers after decimal, add 0 if one digit

牧云@^-^@ 提交于 2021-02-05 07:09:37

问题


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
                    });

回答1:


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




回答2:


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))



回答3:


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/



来源:https://stackoverflow.com/questions/23158086/limit-numbers-after-decimal-add-0-if-one-digit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!