简体   繁体   English

如何在 JavaScript 中四舍五入?

[英]How do I round millions and thousands in JavaScript?

I am trying to round large digits.我正在尝试舍入大数字。 For instance, if I have this number:例如,如果我有这个号码:

12,645,982

I want to round this number and display it as:我想四舍五入这个数字并将其显示为:

13 mil

Or, if I have this number:或者,如果我有这个号码:

1,345

I want to round it and display it as:我想将其四舍五入并将其显示为:

1 thousand

How do I do this in JavaScript or jQuery?我如何在 JavaScript 或 jQuery 中执行此操作?

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参考

Numeral JS .. If someone checks this out please check numeral Js.数字 JS .. 如果有人检查这个,请检查数字 Js。 you just have to include the script and then its just one lineof code你只需要包含脚本,然后它只是一行代码

numeral(yourNumber).format('0.0a')
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/

@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)); 
}
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 语句并且只需要一些数学函数的帮助。

Paul Sweatte's answer is good保罗·斯威特的回答很好

Deepak Thomas's answer is nice迪帕克托马斯的回答很好

My answer is way more 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 :)使用上面的代码,您可以控制十亿、百万或千的小数位数,您还可以控制要显示的单位:)

I modified cetinajero's and Deepak Thomas's awesome answers to also handle negative numbers.我修改了 cetinajero 和 Deepak Thomas 的精彩答案以处理负数。 (and not use ternaries) (并且不使用三元组)

 const numRound = (number) => { let num = number; num = Number(num); const billions = num / 1.0e9; const millions = num / 1.0e6; const thousands = num / 1.0e3; if (Math.abs(num) >= 1.0e9 && Math.abs(billions) >= 100) { return `${Math.round(billions)}B` } if (Math.abs(num) >= 1.0e9 && Math.abs(billions) >= 10) { return `${billions.toFixed(1)}B` } if (Math.abs(num) >= 1.0e9) { return `${billions.toFixed(2)}B` } if (Math.abs(num) >= 1.0e6 && Math.abs(millions) >= 100) { return `${Math.round(millions)}M` } if (Math.abs(num) >= 1.0e6 && Math.abs(millions) >= 10) { return `${millions.toFixed(1)}M` } if (Math.abs(num) >= 1.0e6) { return `${millions.toFixed(2)}M` } if (Math.abs(num) >= 1.0e3 && Math.abs(thousands) >= 100) { return `${Math.round(thousands)}K` } if (num >= 1.0e3 && thousands >= 10) { return `${thousands.toFixed(1)}K` } if (Math.abs(num) >= 1.0e3) { return `${thousands.toFixed(1)}K` } return num.toFixed(); }; console.log(numRound(-23400006)) console.log(numRound(1200)) console.log(numRound(654321)) console.log(numRound(12334000060))

Use str.length and the switch case使用str.lengthswitch case

var number=12345;

something like this像这样的东西

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

}

This is an improvement over Deepak Thomas's answer.这是对迪帕克·托马斯的回答的改进。

It handles decimals whenever it's necessary and gives more readability and control over the function.它在必要时处理小数,并提供更多的可读性和对函数的控制。

Run the code snippet to see a 5 alert live demo showing its usage.运行代码片段以查看显示其用法的 5 个警报实时演示。

 function numRound(num) { num = Math.abs(Number(num)) const billions = num/1.0e+9 const millions = num/1.0e+6 const thousands = num/1.0e+3 return num >= 1.0e+9 && billions >= 100 ? Math.round(billions) + "B" : num >= 1.0e+9 && billions >= 10 ? billions.toFixed(1) + "B" : num >= 1.0e+9 ? billions.toFixed(2) + "B" : num >= 1.0e+6 && millions >= 100 ? Math.round(millions) + "M" : num >= 1.0e+6 && millions >= 10 ? millions.toFixed(1) + "M" : num >= 1.0e+6 ? millions.toFixed(2) + "M" : num >= 1.0e+3 && thousands >= 100 ? Math.round(thousands) + "K" : num >= 1.0e+3 && thousands >= 10 ? thousands.toFixed(1) + "K" : num >= 1.0e+3 ? thousands.toFixed(2) + "K" : num.toFixed() } alert(numRound(1234)) alert(numRound(23456)) alert(numRound(345678)) alert(numRound(4567890)) alert(numRound(56789012))

the simplest way to achieve this is to use Intl api.实现此目的的最简单方法是使用 Intl api。

example:例子:

 const formatter = Intl.NumberFormat('en', {notation: 'compact'}) const K = formatter.format(1555) // thousand const M = formatter.format(1555555) // million const B = formatter.format(1555555555) // billion const T = formatter.format(1555555555555) // trillion console.log(K, M, B, T)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM