You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何去除JavaScript函数返回值的小数部分

去除JavaScript计算结果的小数部分,返回整数的解决方案

你需要的需求完全可以实现,下面是几种常用的取整方法,以及对应修改后的代码:

1. 向下取整(直接舍去小数部分)

使用Math.floor(),会把数值向最小的整数方向取整,比如13.666会变成13。注意Math的首字母必须大写,这是新手容易出错的点。

修改后的代码:

function studentsPerAdmin(students, teachers, helpers) {
  const average = students / (teachers + helpers);
  const integerAverage = Math.floor(average);
  if (average > 10) {
    console.log(`There are on average ${integerAverage} students for each educator.`);
  } else {
    console.log('Unfortunately this class will be cancelled due to not having enough students enrolled.');
  }
  return integerAverage;
}

studentsPerAdmin(41, 1, 2); // 输出:There are on average 13 students for each educator.

2. 四舍五入取整

使用Math.round(),按照常规的四舍五入规则处理,13.666会变成14,13.4则会变成13。

替换代码里的Math.floor为Math.round即可:

const integerAverage = Math.round(average);

3. 向上取整(无论小数多少都进一位)

使用Math.ceil(),只要有小数部分就向上进一位,13.1也会变成14,适合需要确保不低估数量的场景。

替换代码:

const integerAverage = Math.ceil(average);

4. 直接截断小数(快速取整)

还可以用parseInt()、~~或者| 0的方式直接截断小数部分,对于正数来说效果和Math.floor()一致,写法更简洁:

// 三种写法任选其一
const integerAverage = parseInt(average);
const integerAverage = ~~average;
const integerAverage = average | 0;

以上几种方法都能满足你去除小数部分返回整数的需求,可以根据实际业务场景选择合适的取整方式。

内容的提问来源于stack exchange,提问作者Mike.L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 18:12:49