大きな数字を丸めようとしています。たとえば、この番号がある場合:
12,645,982
この数値を四捨五入して、次のように表示します。
13 mil
または、この番号がある場合:
1,345
丸めて次のように表示したい:
1 thousand
JavaScript または jQuery でこれを行うにはどうすればよいですか?
大きな数字を丸めようとしています。たとえば、この番号がある場合:
12,645,982
この数値を四捨五入して、次のように表示します。
13 mil
または、この番号がある場合:
1,345
丸めて次のように表示したい:
1 thousand
JavaScript または jQuery でこれを行うにはどうすればよいですか?
以下は、数千、数百万、数十億をフォーマットするユーティリティ関数です。
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,""))
参考文献
数値 JS .. 誰かがこれをチェックしたら、数値 Js をチェックしてください。スクリプトをインクルードするだけで、コードは 1 行だけです。
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"));
これを出力します:
9 billion
12 million
346 thousand
678
楽しんで。これは正常に機能し、自分で何かをしたことがわからないため、これは難読化されています。
jsfiddleに実際の例があります:jsfiddle.net/p8pfB/
var number = 1345;
var zeroCount = 3;
var roundedNumber = Math.round( number / Math.pow(10,zeroCount) )
zeroCount を数千の場合は 3、数百万の場合は 6 などに調整するだけです。if ステートメントを使用でき、数学関数の助けが必要なだけだと思います。
用途str.length  とswitchケース
var number=12345;
このようなもの
switch (number.length) {
  case 4:
    alert(number/10000+"Thousand");
    break;
}
これは、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))