jquery - toFixed但不是toFixed

时间:2011-01-28 06:40:32

标签: javascript integer decimal

使用 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”。

帮助!

3 个答案:

答案 0 :(得分:2)

您可以使用正则表达式删除尾随.0(如果存在):

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

答案 1 :(得分:1)

这就是我所做的,每次都有效。

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

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

alert( x );

我只是比较两种类型,看看它们是否匹配。如果他们这样做,那么我知道可能有或没有额外的零。无论哪种方式,我只是向上(ceil)或向下(floor)得到整数,没有恼人的小数和尾随零。

答案 2 :(得分:0)

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

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