我如何在 JavaScript 中舍入数百万和数千?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12900332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:22:44  来源:igfitidea点击:

How do I round millions and thousands in JavaScript?

javascriptjqueryroundingnumber-formattingshorthand

提问by denis

I am trying to round large digits. For instance, if I have this number:

我正在尝试舍入大数字。例如,如果我有这个号码:

12,645,982

12,645,982

I want to round this number and display it as:

我想把这个数字四舍五入并将其显示为:

13 mil

13 mil

Or, if I have this number:

或者,如果我有这个号码:

1,345

1,345

I want to round it and display it as:

我想把它四舍五入并将其显示为:

1 thousand

1 thousand

How do I do this in JavaScript or jQuery?

我如何在 JavaScript 或 jQuery 中执行此操作?

回答by Paul Sweatte

Here is a utility function to format thousands, millions, and billions:

这是一个用于格式化数千、数百万和数十亿的实用函数:

function MoneyFormat(labelValue) 
  {
  // Nine Zeroes for Billions
  return Math.abs(Number(labelValue)) >= 1.0e+9

       ? Math.abs(Number(labelValue)) / 1.0e+9 + "B"
       // Six Zeroes for Millions 
       : Math.abs(Number(labelValue)) >= 1.0e+6

       ? Math.abs(Number(labelValue)) / 1.0e+6 + "M"
       // Three Zeroes for Thousands
       : Math.abs(Number(labelValue)) >= 1.0e+3

       ? Math.abs(Number(labelValue)) / 1.0e+3 + "K"

       : Math.abs(Number(labelValue));

   }

Usage:

用法:

   var foo = MoneyFormat(1355);
   //Reformat result to one decimal place
   console.log(parseFloat(foo).toPrecision(2) + foo.replace(/[^B|M|K]/g,""))

References

参考

回答by Vatsal

Numeral JS .. If someone checks this out please check numeral Js. you just have to include the script and then its just one lineof code

数字 JS .. 如果有人检查这个,请检查数字 Js。你只需要包含脚本,然后它只是一行代码

numeral(yourNumber).format('0.0a')

回答by GottZ

var lazyround = function (num) {
    var parts = num.split(",");
    return parts.length > 1 ? (Math.round(parseInt(parts.join(""), 10) / Math.pow(1000, parts.length-1)) + " " + ["thousand", "million", "billion"][parts.length-2]) : parts[0];
};

alert(lazyround("9,012,345,678"));
alert(lazyround("12,345,678"));
alert(lazyround("345,678"));
alert(lazyround("678"));

it outputs this:

它输出这个:

9 billion
12 million
346 thousand
678

have fun. this works fine and since i dont see that you did anything yourself this is obfuscated.

玩得开心。这工作正常,因为我没有看到你自己做了任何事情,所以这被混淆了。

there you have a working example in jsfiddle: jsfiddle.net/p8pfB/

在 jsfiddle 中有一个工作示例:jsfiddle.net/p8pfB/

回答by Deepak Thomas

@Paul's answer is great, but it gives 773.282600918 M etc.

@Paul 的回答很好,但它给出了 773.282600918 M 等。

We probably dont want it for big numbers. Fixed using Math.round()

我们可能不希望它用于大数字。使用 Math.round() 修复

function moolah_round(num,locale='en') {
    // Nine Zeroes for Billions
    return Math.abs(Number(num)) >= 1.0e+9
        ? Math.round(Math.abs(Number(num)) / 1.0e+9 ) + " B"
        // Six Zeroes for Millions
        : Math.abs(Number(num)) >= 1.0e+6
            ? Math.round(Math.abs(Number(num)) / 1.0e+6 ) + " M"
            // Three Zeroes for Thousands
            : Math.abs(Number(num)) >= 1.0e+3
                ? Math.round(Math.abs(Number(num)) / 1.0e+3 ) + " K"
                : Math.abs(Number(num)); 
}

回答by Great Turtle

var number = 1345;
var zeroCount = 3;
var roundedNumber = Math.round( number / Math.pow(10,zeroCount) )

Just adjust the zeroCount to the 3 for thousands, 6 for millions, etc. I'm assuming you can use if statements and just need some help with the math functions.

只需将 zeroCount 调整为 3 为千,6 为百万,等等。我假设您可以使用 if 语句并且只需要一些数学函数的帮助。

回答by StaticVariable

Use str.lengthand the switchcase

用途str.lengthswitch案例

var number=12345;

something like this

像这样的东西

switch (number.length) {
  case 4:
    alert(number/10000+"Thousand");
    break;

}

回答by ii iml0sto1

Paul Sweatte's answer is good

保罗斯威特的回答很好

Deepak Thomas's answer is nice

迪帕克·托马斯的回答很好

My answer is way flexible/customizable and easier to read, so here goes:

我的答案是灵活/可定制且更易于阅读,所以这里是:

Code

代码

function NumbFormat(options) {

  let number = Math.abs(Number(options.number));

  // Nine zeros for Billions
  if (Number(number) >= 1.0e+9) {
    return (number / 1.0e+9).toFixed(options.billion.decimal) + ` ${options.billion.unit}`;
  }

  // Six zeros for Millions
  if (Number(number) >= 1.0e+6) {
    return (number / 1.0e+6).toFixed(options.million.decimal) + ` ${options.million.unit}`;
  }

  // Thrhee zeros for Thousands
  if (Number(number) >= 1.0e+3) {
    return (number / 1.0e+3).toFixed(options.thousand.decimal) + ` ${options.thousand.unit}`;
  }

  return number;
}

console.log(NumbFormat({
  'number': 100000000,
  'billion': {
    'decimal': 1,
    'unit': 'B',
  },
  'million': {
    'decimal': 1,
    'unit': 'M',
  },
  'thousand': {
    'decimal': 1,
    'unit': 'K',
  },
}));

console.log(NumbFormat({
  'number': 100000000,
  'billion': {
    'decimal': 1,
    'unit': 'B',
  },
  'million': {
    'decimal': 1,
    'unit': 'Million',
  },
  'thousand': {
    'decimal': 1,
    'unit': 'K',
  },
}));

console.log(NumbFormat({
  'number': 100000000,
  'billion': {
    'decimal': 1,
    'unit': 'B',
  },
  'million': {
    'decimal': 0,
    'unit': 'Million',
  },
  'thousand': {
    'decimal': 1,
    'unit': 'K',
  },
}));

console.log(NumbFormat({
  'number': 100000000,
  'billion': {
    'decimal': 1,
    'unit': 'B',
  },
  'million': {
    'decimal': 0,
    'unit': 'M',
  },
  'thousand': {
    'decimal': 1,
    'unit': 'K',
  },
}));

With the above code you are in control of how many decimals you want for billions, millions or thousands, you are also in control of which unit you wish to display :)

使用上面的代码,您可以控制十亿、百万或千的小数位数,您还可以控制要显示的单位:)