Javascript:Round Half即使是最后2位数

时间:2015-04-03 11:29:19

标签: javascript math rounding

你好专家,

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.439999999996或123.45999999

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

提前谢谢。

4 个答案:

答案 0 :(得分:1)

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

但是有数字问题 - 大多数实数could not be exactly represented in float formats,所以123.45的存储方式与123.449999999996类似,因此舍入可能会产生意外结果。

<强> UPD: 您在评论中注意到您需要为总计算计算舍入值。然后你最好用20 * X 整数值(精确算术)进行所有计算,并且只对最终结果进行除法和舍入!

答案 1 :(得分:0)

你可以这样做

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

答案 2 :(得分:0)

使用
    Math.round(num * 100)/ 100

答案 3 :(得分:-1)

检查值是否可被0.05整除。如果是,则不需要更改值。如果不是,则需要对该数字进行舍入。你可以通过将值乘以10,然后将其四舍五入到最接近的整数然后将该数除以10来实现。

var round = function (total) {

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

顺便说一下,下次显示你提问时你尝试过的东西。 :)

相关问题