xie*_*ils 72 javascript format jquery numbers
有没有一种简单的方法来格式化JavaScript中的数字,类似于C#(或VB.NET)中可用的格式化方法ToString("format_provider")或String.Format()?
rah*_*hul 76
通常
在jQuery中
Vis*_*rot 47
是的,肯定有一种方法可以在javascript中正确格式化数字,例如:
var val=2489.8237
val.toFixed(3) //returns 2489.824 (round up)
val.toFixed(2) //returns 2489.82
val.toFixed(7) //returns 2489.8237000 (padding)
Run Code Online (Sandbox Code Playgroud)
随着variablename的使用.toFixed.
还有另一个功能toPrecision().有关更多详细信息,您也可以访问
http://raovishal.blogspot.com/2012/01/number-format-in-javascript.html
jfr*_*d00 24
这是一个简单的JS函数,用于将逗号添加到字符串格式的整数中.它将处理整数或十进制数.您可以传递数字或字符串.它显然返回一个字符串.
function addCommas(str) {
var parts = (str + "").split("."),
main = parts[0],
len = main.length,
output = "",
first = main.charAt(0),
i;
if (first === '-') {
main = main.slice(1);
len = main.length;
} else {
first = "";
}
i = len - 1;
while(i >= 0) {
output = main.charAt(i) + output;
if ((len - i) % 3 === 0 && i > 0) {
output = "," + output;
}
--i;
}
// put sign back
output = first + output;
// put decimal part back
if (parts.length > 1) {
output += "." + parts[1];
}
return output;
}
Run Code Online (Sandbox Code Playgroud)
这是一组测试用例:http://jsfiddle.net/jfriend00/6y57j/
您可以在之前的jsFiddle中看到它被使用:http://jsfiddle.net/jfriend00/sMnjT/.您可以通过简单的Google搜索"javascript add逗号"找到可以处理十进制数字的函数.
将数字转换为字符串可以通过多种方式完成.最简单的方法是将其添加到字符串中:
var myNumber = 3;
var myStr = "" + myNumber; // "3"
Run Code Online (Sandbox Code Playgroud)
在你的jsFiddle的上下文中,你可以通过改变这一行来得到逗号:
jTarget.text(current);
Run Code Online (Sandbox Code Playgroud)
对此:
jTarget.text(addCommas(current));
Run Code Online (Sandbox Code Playgroud)
你可以在这里看到它:http://jsfiddle.net/jfriend00/CbjSX/
pat*_*ick 12
我写了一个简单的函数(还不是另一个需要的jQuery插件!!),如果数字不是一个开头的数字,它会将数字转换为十进制分隔的字符串或空字符串:
function format(x) {
return isNaN(x)?"":x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Run Code Online (Sandbox Code Playgroud)
format(578999); 结果是 578,999
format(10); 结果是 10
如果你想要一个小数点而不是一个逗号,只需用小数点替换代码中的逗号.
其中一条评论正确地表明这只适用于整数,只需要一些小的修改,你就可以使它适用于浮点数:
function format(x) {
if(isNaN(x))return "";
n= x.toString().split('.');
return n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")+(n.length>1?"."+n[1]:"");
}
Run Code Online (Sandbox Code Playgroud)
以下是一些解决方案,全部通过测试套件,测试套件和基准测试,如果要复制和粘贴测试,请尝试使用此Gist.
基于/sf/answers/1009983831/,但如果没有小数点则修复.
if (typeof Number.prototype.format === 'undefined') {
Number.prototype.format = function (precision) {
if (!isFinite(this)) {
return this.toString();
}
var a = this.toFixed(precision).split('.');
a[0] = a[0].replace(/\d(?=(\d{3})+$)/g, '$&,');
return a.join('.');
}
}
Run Code Online (Sandbox Code Playgroud)
if (typeof Number.prototype.format1 === 'undefined') {
Number.prototype.format1 = function (precision) {
if (!isFinite(this)) {
return this.toString();
}
var a = this.toFixed(precision).split('.'),
// skip the '-' sign
head = Number(this < 0);
// skip the digits that's before the first thousands separator
head += (a[0].length - head) % 3 || 3;
a[0] = a[0].slice(0, head) + a[0].slice(head).replace(/\d{3}/g, ',$&');
return a.join('.');
};
}
Run Code Online (Sandbox Code Playgroud)
if (typeof Number.prototype.format2 === 'undefined') {
Number.prototype.format2 = function (precision) {
if (!isFinite(this)) {
return this.toString();
}
var a = this.toFixed(precision).split('.');
a[0] = a[0]
.split('').reverse().join('')
.replace(/\d{3}(?=\d)/g, '$&,')
.split('').reverse().join('');
return a.join('.');
};
}
Run Code Online (Sandbox Code Playgroud)
if (typeof Number.prototype.format3 === 'undefined') {
Number.prototype.format3 = function (precision) {
if (!isFinite(this)) {
return this.toString();
}
var a = this.toFixed(precision).split('');
a.push('.');
var i = a.indexOf('.') - 3;
while (i > 0 && a[i-1] !== '-') {
a.splice(i, 0, ',');
i -= 3;
}
a.pop();
return a.join('');
};
}
Run Code Online (Sandbox Code Playgroud)
console.log('======== Demo ========')
var n = 0;
for (var i=1; i<20; i++) {
n = (n * 10) + (i % 10)/100;
console.log(n.format(2), (-n).format(2));
}
Run Code Online (Sandbox Code Playgroud)
如果我们想要自定义千位分隔符或小数分隔符,请使用replace():
123456.78.format(2).replace(',', ' ').replace('.', ' ');
Run Code Online (Sandbox Code Playgroud)
function assertEqual(a, b) {
if (a !== b) {
throw a + ' !== ' + b;
}
}
function test(format_function) {
console.log(format_function);
assertEqual('NaN', format_function.call(NaN, 0))
assertEqual('Infinity', format_function.call(Infinity, 0))
assertEqual('-Infinity', format_function.call(-Infinity, 0))
assertEqual('0', format_function.call(0, 0))
assertEqual('0.00', format_function.call(0, 2))
assertEqual('1', format_function.call(1, 0))
assertEqual('-1', format_function.call(-1, 0))
// decimal padding
assertEqual('1.00', format_function.call(1, 2))
assertEqual('-1.00', format_function.call(-1, 2))
// decimal rounding
assertEqual('0.12', format_function.call(0.123456, 2))
assertEqual('0.1235', format_function.call(0.123456, 4))
assertEqual('-0.12', format_function.call(-0.123456, 2))
assertEqual('-0.1235', format_function.call(-0.123456, 4))
// thousands separator
assertEqual('1,234', format_function.call(1234.123456, 0))
assertEqual('12,345', format_function.call(12345.123456, 0))
assertEqual('123,456', format_function.call(123456.123456, 0))
assertEqual('1,234,567', format_function.call(1234567.123456, 0))
assertEqual('12,345,678', format_function.call(12345678.123456, 0))
assertEqual('123,456,789', format_function.call(123456789.123456, 0))
assertEqual('-1,234', format_function.call(-1234.123456, 0))
assertEqual('-12,345', format_function.call(-12345.123456, 0))
assertEqual('-123,456', format_function.call(-123456.123456, 0))
assertEqual('-1,234,567', format_function.call(-1234567.123456, 0))
assertEqual('-12,345,678', format_function.call(-12345678.123456, 0))
assertEqual('-123,456,789', format_function.call(-123456789.123456, 0))
// thousands separator and decimal
assertEqual('1,234.12', format_function.call(1234.123456, 2))
assertEqual('12,345.12', format_function.call(12345.123456, 2))
assertEqual('123,456.12', format_function.call(123456.123456, 2))
assertEqual('1,234,567.12', format_function.call(1234567.123456, 2))
assertEqual('12,345,678.12', format_function.call(12345678.123456, 2))
assertEqual('123,456,789.12', format_function.call(123456789.123456, 2))
assertEqual('-1,234.12', format_function.call(-1234.123456, 2))
assertEqual('-12,345.12', format_function.call(-12345.123456, 2))
assertEqual('-123,456.12', format_function.call(-123456.123456, 2))
assertEqual('-1,234,567.12', format_function.call(-1234567.123456, 2))
assertEqual('-12,345,678.12', format_function.call(-12345678.123456, 2))
assertEqual('-123,456,789.12', format_function.call(-123456789.123456, 2))
}
console.log('======== Testing ========');
test(Number.prototype.format);
test(Number.prototype.format1);
test(Number.prototype.format2);
test(Number.prototype.format3);
Run Code Online (Sandbox Code Playgroud)
function benchmark(f) {
var start = new Date().getTime();
f();
return new Date().getTime() - start;
}
function benchmark_format(f) {
console.log(f);
time = benchmark(function () {
for (var i = 0; i < 100000; i++) {
f.call(123456789, 0);
f.call(123456789, 2);
}
});
console.log(time.format(0) + 'ms');
}
async = [];
function next() {
setTimeout(function () {
f = async.shift();
f && f();
next();
}, 10);
}
console.log('======== Benchmark ========');
async.push(function () { benchmark_format(Number.prototype.format); });
async.push(function () { benchmark_format(Number.prototype.format1); });
async.push(function () { benchmark_format(Number.prototype.format2); });
async.push(function () { benchmark_format(Number.prototype.format3); });
next();
Run Code Online (Sandbox Code Playgroud)