Javascript:Round Half偶数后2位

Javascript: Round Half Even last 2 digits

本文关键字:2位 Half Round Javascript      更新时间:2023-09-26

大家好,

var total1 = 123.44;  //how do i round this up to 123.40?
var total2 = 123.45;  //this value stay (no changes)
var total3 = 123.46;  //how do i round this up to 123.50?

我想做的是:

    total = totalfromdb;  
    GST = total*6/100;  //<--- This value needed to round half even as mentioned above
    GSTadjust = ???????;  //<--- How do i get the total different from GST (round half even above)?
    grandtotal = parseInt(GST) + parseInt(total);  //<--- This value for mygrandtotal

问题在代码中。我如何将.44到.40和.46到.50取整和/或获得不同的值,例如:

.44到.40,不同的值为-4(显示在页面上)。

.46到.50,不同的值为+4(显示在页面上)。

我需要取整一半的值甚至可能是123.4399999999996或123.45999999

我已经按照Matti Mehtonen的建议编辑了我的问题。

提前谢谢。

您可以执行此

var round_half = function(num) {
    if ((num * 100) % 10 != 5) {
        num = (Math.round(num * 10) / 10).toFixed(2);
    }
    return num;
}

在数学意义上:
RoundANumberDownward(total * 20) / 20 //does Floor function exist in JS?

但也存在数字问题——大多数实数无法以浮点格式准确表示,因此123.45的存储方式与123.449999999996类似,因此四舍五入可能会产生意外结果。

Upd:您在评论中注意到,您需要四舍五入的值来计算总计。然后,您最好使用20*Xinteger值(精确算术)进行所有计算,并只对最终结果进行除法和四舍五入!

使用
数学圆形(num*100)/100

检查值是否可被0.05整除。如果是,则不需要更改值。如果不是,那么你需要四舍五入这个数字。您可以将值乘以10,然后四舍五入到最接近的整数,然后将该数字除以10。

var round = function (total) {
    if (total % 0.05 === 0) {
        return total;
    } else {
        return Math.round(total * 10) / 10;
    }
};

顺便说一句,下次当你问问题时,展示你已经尝试过的东西。:)