javascript - how to prevent toFixed from rounding off decimal numbers

前端 未结 5 1456
栀梦
栀梦 2020-11-28 14:29

I\'m very new to html, javascript, and css so please forgive if my question sounds idiotic to you. My question is how can I prevent the function toFixed() from

5条回答
  •  难免孤独
    2020-11-28 15:25

    Round the number (down) to the nearest cent first:

    val = Math.floor(100 * val) / 100;
    

    EDIT It's been pointed out that this fails for e.g. 1.13. I should have known better myself!

    This fails because the internal floating point representation of 1.13 is very slightly less than 1.13 - multiplying that by 100 doesn't produce 113 but 112.99999999999998578915 and then rounding that down takes it to 1.12

    Having re-read the question, it seems that you're really only trying to perform input validation (see below), in which case you should use normal form validation techniques and you shouldn't use .toFixed() at all. That function is for presenting numbers, not calculating with them.

    $('#txtAmount').on('keypress', function (e) {
        var k = String.fromCharCode(e.charCode);
        var v = this.value;
        var dp = v.indexOf('.');
    
        // reject illegal chars
        if ((k < '0' || k > '9') && k !== '.') return false;
    
        // reject any input that takes the length
        // two or more beyond the decimal point
        if (dp >= 0 && v.length > dp + 2) {
            return false;
        }
    
        // don't accept >1 decimal point, or as first char
        if (k === '.' && (dp >= 0 || v.length === 0)) {
            return false;
        }
    });
    

提交回复
热议问题