javascript - how to prevent toFixed from rounding off decimal numbers

跟風遠走 提交于 2019-11-27 02:01:22

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

That's even simpler:

function truncateToDecimals(num, dec = 2) {
  const calcDec = Math.pow(10, dec);
  return Math.trunc(num * calcDec) / calcDec;
}

So:

truncateToDecimals(123456.786) -> 123456.78

you can give this a try, it won't round your decimals

/**
 * @param {any} input 
 * @param {number} decimals 
 */
var toFixed = function(input, decimals) {
  var arr = ("" + input).split(".");
  if (arr.length === 1) return input;
  var int = arr[0],
      max = arr[1].length,
      dec = arr[1].substr(0, decimals > max ? max : decimals);
  return decimals === 0 ? int : [int, "." , dec].join("");
}
Quiams

Additionally, to prevent toFixed() from rounding off decimal numbers and to make your number into two decimal places you can use this,

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

if you want to avoid rounding off... Ex. 1.669 => 1.67, 548.466 => 548.47

The function result looks like: 1.669 => 1.66, 548.466 => 548.46

Then the following JQuery function will help you. It is tested and working properly.

<input name="a" type="text" id="a" size="7%" tabindex="2">




  $('#a').keyup(function(e){
        if($(this).val().indexOf('.')!=-1){ 
            if($(this).val()=="." && $(this).val().length==1){
                this.value = parseFloat(0).toFixed(1);
            }else if($(this).val().split(".")[1].length > 2){                
                if( isNaN( parseFloat( this.value ) ) ) 
                    return;
                  this.value = $(this).val().split(".")[0]+"."+$(this).val().split(".")[1].substring(0,2);
            }   
        }
   });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!