我有一个除法的结果,我希望放弃结果数的小数部分。

我该怎么做呢?


当前回答

在ES2015中,Math.trunc()是可用的。

Math.trunc(2.3)                       // 2
Math.trunc(-2.3)                      // -2
Math.trunc(22222222222222222222222.3) // 2.2222222222222223e+22
Math.trunc("2.3")                     // 2
Math.trunc("two")                     // NaN
Math.trunc(NaN)                       // NaN

IE11及以下版本不支持,但在Edge和其他现代浏览器中都可以运行。

其他回答

如果不关心舍入,只需将数字转换为字符串,然后删除句号之后的所有内容,包括句号。不管有没有小数点,这个都成立。

const sEpoch = ((+new Date()) / 1000).toString();
const formattedEpoch = sEpoch.split('.')[0];

例如:

var x = 9.656;
x.toFixed(0);           // returns 10
x.toFixed(2);           // returns 9.66
x.toFixed(4);           // returns 9.6560
x.toFixed(6);           // returns 9.656000 

or

parseInt("10");         // returns 10
parseInt("10.33");      // returns 10
parseInt("10 20 30");   // returns 10
parseInt("10 years");   // returns 10
parseInt("years 10");   // returns NaN  

对于ES6实现,使用如下代码:

const millisToMinutesAndSeconds = (millis) => {
  const minutes = Math.floor(millis / 60000);
  const seconds = ((millis % 60000) / 1000).toFixed(0);
  return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
}

U还可以显示小数点后(这里是2位数)的特定数字,使用以下代码:

var num = (15.46974).toFixed(2) 控制台.log(数字) // 15.47 console.log(类型编号) // 字符串

使用Math.round()函数。

Math.round(65.98) // will return 66 
Math.round(65.28) // will return 65