den*_*nis 2 javascript jquery rounding shorthand number-formatting
我想尝试大数字.例如,如果我有这个号码:
12,645,982
我想将这个数字四舍五入并显示为:
13 mil
或者,如果我有这个号码:
1,345
我想围绕它并将其显示为:
1 thousand
我如何在JavaScript或jQuery中执行此操作?
Pau*_*tte 17
这是一个实用功能,可以格式化成千上万,数百万和数十亿:
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));
}
Run Code Online (Sandbox Code Playgroud)
用法:
var foo = MoneyFormat(1355);
//Reformat result to one decimal place
console.log(parseFloat(foo).toPrecision(2) + foo.replace(/[^B|M|K]/g,""))
Run Code Online (Sandbox Code Playgroud)
参考
数字JS ..如果有人检查了这个,请检查数字Js。您只需要包含脚本,然后仅包含一行代码
numeral(yourNumber).format('0.0a')
Run Code Online (Sandbox Code Playgroud)
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"));
Run Code Online (Sandbox Code Playgroud)
它输出这个:
9 billion
12 million
346 thousand
678
Run Code Online (Sandbox Code Playgroud)
玩得开心.这工作正常,因为我没有看到你自己做了什么,这是混淆的.
在jsfiddle中有一个工作示例:jsfiddle.net/p8pfB/
用途str.length 及switch案例
var number=12345;
Run Code Online (Sandbox Code Playgroud)
像这样的东西
switch (number.length) {
case 4:
alert(number/10000+"Thousand");
break;
}
Run Code Online (Sandbox Code Playgroud)