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

discord.js v13如何去除命令冷却提示中的小数部分

Discord.js v13 冷却提示整数秒输出实现

问题场景

开发环境为discord.js v13、Node.js v16,搭建命令冷却系统时,原有代码返回的冷却剩余时间带1位小数(示例输出:4.2s cooldown),需要移除小数部分,实现整数秒提示效果(示例输出:4s cooldown)。
原有问题代码:

if (!cooldowns.has(command.name)) {
  cooldowns.set(command.name, new Discord.Collection());
}
const current_time = Date.now();
const time_stamps = cooldowns.get(command.name);
const cooldown_amount = command.cooldown * 1000;
if (time_stamps.has(message.author.id)) {
  const expiration_time = time_stamps.get(message.author.id) + cooldown_amount;
  if (current_time < expiration_time) {
    const time_left = (expiration_time - current_time) / 1000;
    return message.reply(`${time_left.toFixed(1)}s cooldown`).then((msg) => {
      setTimeout(() => msg.delete(), 3000);
    });
  }
}
time_stamps.set(message.author.id, current_time);
setTimeout(() => time_stamps.delete(message.author.id), cooldown_amount);

问题原因

返回值带小数的直接原因是代码中使用time_left.toFixed(1)方法,强制将剩余秒数保留1位小数输出。

修改方案

只需要替换原有toFixed(1)的逻辑,对计算得到的秒数做整数取整处理即可,Node.js v16原生支持所有Math取整方法,无需额外依赖,可根据业务需求选择对应取整规则:

  • 直接截断小数(完全匹配“移除小数部分”需求):使用Math.trunc(time_left),无论小数点后数值是多少直接舍去,例如4.9秒会显示为4秒
  • 四舍五入取整:使用Math.round(time_left),按小数点后数值做四舍五入,例如4.2秒显示4秒、4.6秒显示5秒
  • 向上取整(防用户卡秒触发):使用Math.ceil(time_left),只要有小数部分就进1,例如4.1秒会显示为5秒,避免提示的剩余时间比实际冷却时间短
    修改后的完整可运行代码(以直接截断小数为例):
if (!cooldowns.has(command.name)) {
  cooldowns.set(command.name, new Discord.Collection());
}
const current_time = Date.now();
const time_stamps = cooldowns.get(command.name);
const cooldown_amount = command.cooldown * 1000;
if (time_stamps.has(message.author.id)) {
  const expiration_time = time_stamps.get(message.author.id) + cooldown_amount;
  if (current_time < expiration_time) {
    const time_left = (expiration_time - current_time) / 1000;
    return message.reply(`${Math.trunc(time_left)}s cooldown`).then((msg) => {
      setTimeout(() => msg.delete(), 3000);
    });
  }
}
time_stamps.set(message.author.id, current_time);
setTimeout(() => time_stamps.delete(message.author.id), cooldown_amount);

提示:如果需要保留toFixed的写法,也可以直接将toFixed(1)的参数改为0,即time_left.toFixed(0),效果等同于四舍五入取整。

内容的提问来源于stack exchange,提问作者Pooyan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 01:12:45