javascript - 如何防止toFixed舍入十进制数 [英] javascript - how to prevent toFixed from rounding off decimal numbers

查看:157
本文介绍了javascript - 如何防止toFixed舍入十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对html,javascript和css很新,所以请原谅我的问题听起来很愚蠢。我的问题是如何从十进制数的四舍五入中阻止函数 toFixed()

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.

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

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

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.

测试输入:


  Input         Output  
123456.781 -> 123456.78

123456.786 -> 123456.79

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

Why my code does not allow arrow keys in chrome?

请帮忙。如果您有更好的解决方案,您可以自由建议。在此先感谢。

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

推荐答案

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

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

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

编辑有人指出,这例如失败了1.13。我自己应该知道的更好!

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

这是失败的,因为1.13的内部浮点表示略小于1.13 - 乘以100不会产生113但是112.99999999999998578915然后四舍五入使其达到1.12

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

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

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

这篇关于javascript - 如何防止toFixed舍入十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆