0

我有一个像这样 89.9999 的十进制格式的 API 响应,我已经习惯了 toFixed 并四舍五入到 89.90 。但问题是如果我将值设为 90,因为 toFixed 它显示为 90.00 ,而我只需要 90。是有什么方法可以实现吗?

我尝试进行基本计算的代码是:

 var myPerc= value.studPerc === 0 ? '0' : value.studPerc.toFixed(2); 
4

4 回答 4

2

您可以先使用模数%来检测值是否为小数,因此您可以像下面那样进行

var value = n % 1 !== 0 ? n.toFixed(2) : n;
于 2018-04-20T07:29:13.717 回答
1

你可以这样做来检查使用%

每当我们使用Integer%1它时0,如果我们使用Float%1它将返回一些点值,例如0.####.

演示

function setToFixed(v) {
  console.log(v % 1 ? v.toFixed(2) : v)
}

setToFixed(90)


setToFixed(89.7589999)
.as-console-wrapper { max-height: 100% !important; top: 0; }

于 2018-04-20T07:28:35.400 回答
0

使用sliceaftertoFixed删除尾随(.00如果存在):

const getPerc = num => {
  const str = num.toFixed(2);
  if (str.slice(-2) === '00') return str.slice(0, str.length - 3);
  return str;
}
console.log(getPerc(90));
console.log(getPerc(89.9999));
console.log(getPerc(89.55));

于 2018-04-20T07:25:51.593 回答
0

你可以试试:

Math.round(value * 100) / 100
于 2018-04-20T07:28:15.073 回答