【问题标题】:Splicing a number in javascript在javascript中拼接一个数字
【发布时间】:2021-08-24 00:33:12
【问题描述】:

我正在尝试编写 1k 10k 和 100k 并且我正在尝试找到 .splice 的一种形式,但是对于这样的数字,我可以将 1000、10000 和 100000 转换为 k,同时对每个数字使用相同的公式。

【问题讨论】:

    标签: javascript slice


    【解决方案1】:

    除以 1000。

    [1000, 10000, 100000].forEach(x => console.log(x / 1000 + 'k'));

    在需要时显示一位小数:

    [1320, 14302, 193234].forEach(x => console.log(+(x / 1000).toFixed(1) + 'k'))

    【讨论】:

    • 现在这个答案确实有效,但我也希望能够显示第一个小数位,例如 1320 将显示 1.3k,14.302 将显示 14.3k,193234 将显示 193.2k,有没有办法使用相同的公式来做到这一点?
    • [1320, 193234].forEach(x => console.log(+(x / 1000).toFixed(1) + 'k'))
    • @HelpMeWithJavascript 很高兴为您提供帮助。
    • 谢谢我接受了!我只需要稍等片刻才能让我接受它,因为这个问题基本上是刚刚发布的! :D
    【解决方案2】:

    您可以使用substring() 获取从开头到字符串长度减3的所有字符,然后将句点和倒数第二个位置的字符连接起来:

    function format(s) {
      s = String(s)
      return s.substring(0, s.length - 3) + "." + s.substring(s.length - 3, s.length - 2) + 'k';
    }
    console.log(format(1000))
    console.log(format(1100))
    console.log(format(10000))
    console.log(format(11000))

    如果数字小于 1000,我们可以执行长度检查,如果字符串的长度小于 4,则在结果前面加上 0

    function format(s) {
      s = String(s)
      return (s.length < 4 ? '0' : s.substring(0, s.length - 3)) + "." + s.substring(s.length - 3, s.length - 2) + 'k';
    }
    console.log(format(100))
    console.log(format(1000))
    console.log(format(1100))
    console.log(format(10000))
    console.log(format(11000))

    【讨论】:

    • 在函数内部转换为字符串而不是期望字符串可能会更好的用户体验,例如如果你给它 10 也不起作用
    • 对于十进制数似乎也不太适用,使它们大 100 倍,小数点后 1 位,添加的小数越多效果越好 :)
    【解决方案3】:

    function kFormatter(num) {
      return Math.abs(num) >= 1000 ? Math.sign(num) * ((Math.abs(num) / 1000).toFixed(1)) + 'k' : Math.sign(num) * Math.abs(num)
    }
    
    console.log(kFormatter(1200)); // 1.2k
    console.log(kFormatter(-1200)); // -1.2k
    console.log(kFormatter(999.9)); // 999.9
    console.log(kFormatter(-900)); // -900

    【讨论】:

    • 尝试输入999.1,会得到错误的结果
    • 对不起,我的错误我更新了答案应该是 num >= 1000
    猜你喜欢
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 2014-03-15
    • 2015-05-18
    • 1970-01-01
    • 2015-11-26
    相关资源
    最近更新 更多