【问题标题】:how to convert integer in to specific string based on value [closed]如何根据值将整数转换为特定字符串[关闭]
【发布时间】:2020-09-01 22:38:12
【问题描述】:

我在一个 sqlite 数据库中有不同的用户,我想要一种根据数量将它们转换为字符串的方法。

假设我有 10000x 的用户 1,它将被转换为 10K。或者用户 2 的 500000x 将转换为 500K,或者用户 3 的 10500000 将转换为 10.5M。我该怎么做?

【问题讨论】:

标签: javascript node.js string integer discord.js


【解决方案1】:

一点点数学就能帮你搞定:

const convert = (n) => {
  const units = ['', 'K', 'M', 'G', 'T', 'P'];
  const p = Math.floor(Math.log10(n) / 3);
  
  return n / Math.pow(10, p * 3) + units[p];
};

console.log(convert(1000));
console.log(convert(50000));
console.log(convert(10500000));

【讨论】:

  • 哇,我从来不知道数学可以做到这一点
猜你喜欢
  • 1970-01-01
  • 2015-07-27
  • 2016-02-18
  • 2012-11-04
  • 2012-05-01
  • 1970-01-01
  • 2020-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多