2011-01-28 106 views
3

使用toFixed喜欢如下给出:jQuery的 - toFixed但不toFixed

var a=0.5, b=1, c=1.5; 
console.log(a.toFixed(), b.toFixed(), c.toFixed()); 
// 0.5 1.0 1.5 

然而,当它是一个整数,我只希望它回到 “1”。

帮助!

+2

http://stackoverflow.com/questions/1393332/javascript-tofixed-function – 2011-01-28 06:47:34

+1

这个问题其实跟jquery没有关系。 toFixed被内置到JavaScript中。 – greggreg 2011-01-28 06:52:20

回答

2

你可以使用正则表达式来删除尾随.0,如果它存在:

Number.prototype.safe_toFixed = function (x) { 
    var that = this.toFixed(x); 
    return that.replace(/\.0$/, ''); 
} 
0

你可以使用split()if条件:

var digit = 1.2 
    var ret = digit.toFixed(1); 
    var intValue = ret.split('.'); 
    if(intValue[1] == 0){ 
     digit = intValue[0]; 
    } 
1

这是我没有和它每次工作。

var x= Number(54.03).toFixed(1); 

    if(Math.floor(x) == x) { 
    x = Math.floor(x); 
    } 

alert(x); 

我只是比较两种类型,看看他们是否匹配。如果他们这样做,那么我知道可能有或没有额外的零。无论哪种方式,我只需将(小区)或下(楼层)四舍五入,即可得到整数,而不会产生烦人的小数和零。

相关问题