javascript - 如何防止 toFixed 四舍五入十进制数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10808671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:02:10  来源:igfitidea点击:

javascript - how to prevent toFixed from rounding off decimal numbers

javascripttofixed

提问by TheOnlyIdiot

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 rounding of the decimal number.

我对 html、javascript 和 css 很陌生,所以如果我的问题对你来说很愚蠢,请原谅。我的问题是如何防止函数toFixed()四舍五入十进制数。

Here's my link: http://jsfiddle.net/RWBaA/4/

这是我的链接:http: //jsfiddle.net/RWBaA/4/

What I'm trying to do is I'm checking the input if its a valid decimal number whenever the user types in the textbox. At the same time I also want to check if the input is a valid currency which means it can only add two more numbers at the right of the decimal point. The problem is when the user enters the 3rd number after the decimal point the 2nd number after the decimal point is rounded off to the nearest hundredths if the the 3rd number is >= 5.

我想要做的是,每当用户在文本框中键入时,我都会检查输入是否为有效的十进制数。同时我还想检查输入是否为有效货币,这意味着它只能在小数点右侧再添加两个数字。问题是当用户输入小数点后的第三个数字时,如果第三个数字 >= 5,小数点后的第二个数字将四舍五入到最接近的百分位。

Test Input :

测试输入:

  Input         Output  
123456.781 -> 123456.78

123456.786 -> 123456.79

Why my code does not allow arrow keys in chrome?

为什么我的代码不允许 chrome 中的箭头键?

Please help. If you have a better solution you are free to suggest. Thanks in advance.

请帮忙。如果您有更好的解决方案,您可以自由提出建议。提前致谢。

回答by Alnitak

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

首先将数字(向下)四舍五入到最接近的分:

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

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

编辑有人指出,这在例如 1.13 中失败。我应该更了解自己!

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

这失败了,因为 1.13 的内部浮点表示非常小于 1.13 - 乘以 100 不会产生 113 而是 112.99999999999998578915 然后将其四舍五入到 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 presentingnumbers, not calculating with them.

重新阅读问题后,您似乎真的只是在尝试执行输入验证(见下文),在这种情况下,您应该使用正常的表单验证技术,而根本不应该使用.toFixed()。该函数用于呈现数字,而不是用它们进行计算。

$('#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;
    }
});

回答by David

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

回答by Santiago Hernández

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

回答by Quiams

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

此外,为了防止 toFixed() 四舍五入小数并将您的数字变成两位小数,您可以使用它,

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

回答by Sachin Parse

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

如果你想避免四舍五入......例如。1.669 => 1.67、548.466 => 548.47

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

函数结果如下: 1.669 => 1.66, 548.466 => 548.46

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

那么下面的 JQuery 函数会对你有所帮助。它经过测试并正常工作。

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