在JavaScript中如何对百万和千位数进行四舍五入?

9

我正在尝试将大数字四舍五入。例如,如果我有这个数字:

12,645,982

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

13百万

或者,如果我有这个数字:

1,345

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

1千

我该如何在JavaScript或jQuery中实现?


是的,我对此有一个相当不错的答案,但得等到下次再说了。 - Alexander
10个回答

22

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

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));

   }

用法:

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

参考资料


3
这个很有效。我将其用作 AngularJS 过滤器://添加M、B并对大数四舍五入,如5.3B、6M等。 mm2.filter('bigNumRound', function() { return function (val) { //十亿级别的数字 return Math.abs(Number(val)) >= 1.0e+9 ? Math.abs(Number(val)) / 1.0e+9 + "B" //百万级别的数字 : Math.abs(Number(val)) >= 1.0e+6 ? Math.abs(Number(val)) / 1.0e+6 + "M" //千级别的数字 : Math.abs(Number(val)) >= 1.0e+3 ? Math.abs(Number(val)) / 1.0e+3 + "K" //其他情况直接返回原值 : Math.abs(Number(val)); } });在 HTML 中使用:{{someval | bigNumRound}} - Jazzy
谢谢Paul。这对我很有帮助。我正在添加一个fiddle,可能会帮助其他人看到它的工作原理。http://jsfiddle.net/ykng4tkL/ - Anand G
无三元运算符: // 十亿级别 if (Math.abs(Number(labelValue)) >= 1.0e+9) { return `R$ ${Math.trunc(Math.abs(Number(labelValue)) / 1.0e+9)}B`; } // 百万级别 if (Math.abs(Number(labelValue)) >= 1.0e+6) { return `R$ ${Math.trunc(Math.abs(Number(labelValue)) / 1.0e+6)}M`; } // 千级别 if (Math.abs(Number(labelValue)) >= 1.0e+3) { return `R$ ${Math.trunc(Math.abs(Number(labelValue)) / 1.0e+3)}K`; } return Math.abs(Number(labelValue)); }``` - JorgeMadson

9

Numeral JS .. 如果有人看到这个,请检查一下 Numeral Js。你只需要引入脚本,然后只需一行代码即可。

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

这位朋友们,这才是真正的答案。 - Luis Stanley Jovel

7
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"));

它输出:

9 billion
12 million
346 thousand
678

玩得开心。这个很好用,因为我没有看到你自己做了什么,所以这是被混淆的。

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


3
@Paul的回答很好,但它给出的是773.282600918M等等。对于大数字,我们可能不想要这么精确。可以使用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)); 
}

这样会好很多...能够选择有多少个“小数位”就更好了比如说,不是12m,而是12.1m,或者不是12k,而是12.1k等等。 - ii iml0sto1
@iiiml0sto1 我对这个绝妙的示例进行了一些更改,以便在必要时也可以处理小数。请参见:https://dev59.com/p2nWa4cB1Zd3GeqP2Z-0#68273755 - cetinajero

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

只需将 zeroCount 调整为 3(千位)、6(百万位)等即可。我假设您可以使用 if 语句,只需要在数学函数方面获得一些帮助。


1

Paul Sweatte的回答很好。

Deepak Thomas的回答不错。

我的回答更加灵活/可定制,并且更易于阅读,以下是:

代码

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',
  },
}));

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

1

这是对Deepak Thomas答案的改进。

它在必要时处理小数,并提供更好的可读性和对函数的控制。

运行代码片段以查看一个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))


1
我修改了cetinajero和Deepak Thomas的出色答案,使其也能处理负数(并且不使用三元运算符)。

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))


0
使用 str.lengthswitch case。
var number=12345;

类似这样的东西

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

}

我认为是这样的,因为看起来提问者并没有尝试过去实现它。 - GottZ

0

实现这个最简单的方法是使用Intl API。

例如:

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)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接