有没有办法将数字四舍五入为读者友好的格式? (例如 1100 美元)[已关闭]

2023-11-23

就像 Stack Overflow 声誉四舍五入一样,我希望对货币做同样的事情

1,000 美元 => 1,000 美元

1,000,000 美元 => 100 万美元

我如何在 JavaScript 中(最好是在 jQuery 中)实现这一点?


这是一个简单的函数来做到这一点:

function abbrNum(number, decPlaces) {
  // 2 decimal places => 100, 3 => 1000, etc
  decPlaces = Math.pow(10, decPlaces);

  // Enumerate number abbreviations
  var abbrev = ["k", "m", "b", "t"];

  // Go through the array backwards, so we do the largest first
  for (var i = abbrev.length - 1; i >= 0; i--) {

    // Convert array index to "1000", "1000000", etc
    var size = Math.pow(10, (i + 1) * 3);

    // If the number is bigger or equal do the abbreviation
    if (size <= number) {
      // Here, we multiply by decPlaces, round, and then divide by decPlaces.
      // This gives us nice rounding to a particular decimal place.
      number = Math.round(number * decPlaces / size) / decPlaces;

      // Handle special case where we round up to the next abbreviation
      if ((number == 1000) && (i < abbrev.length - 1)) {
        number = 1;
        i++;
      }

      // Add the letter for the abbreviation
      number += abbrev[i];

      // We are done... stop
      break;
    }
  }

  return number;
}
console.log(abbrNum(1200, 3))

Outputs:

abbrNum(12 , 1)          => 12
abbrNum(0 , 2)           => 0
abbrNum(1234 , 0)        => 1k
abbrNum(34567 , 2)       => 34.57k
abbrNum(918395 , 1)      => 918.4k
abbrNum(2134124 , 2)     => 2.13m
abbrNum(47475782130 , 2) => 47.48b

Demo: http://jsfiddle.net/jtbowden/SbqKL/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有没有办法将数字四舍五入为读者友好的格式? (例如 1100 美元)[已关闭] 的相关文章

随机推荐