Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JavaScript中以逗号作为分隔符打印数字_Javascript_Formatting_Numbers_Integer - Fatal编程技术网

如何在JavaScript中以逗号作为分隔符打印数字

如何在JavaScript中以逗号作为分隔符打印数字,javascript,formatting,numbers,integer,Javascript,Formatting,Numbers,Integer,我正在尝试以逗号作为千位分隔符打印一个整数。例如,我想将数字1234567显示为“1234567”。我该怎么做呢 我是这样做的: function numberWithCommas(x) { x = x.toString(); var pattern = /(-?\d+)(\d{3})/; while (pattern.test(x)) x = x.replace(pattern, "$1,$2"); return x; } 有没有更简单或更优雅

我正在尝试以逗号作为千位分隔符打印一个整数。例如,我想将数字1234567显示为“1234567”。我该怎么做呢

我是这样做的:

function numberWithCommas(x) {
    x = x.toString();
    var pattern = /(-?\d+)(\d{3})/;
    while (pattern.test(x))
        x = x.replace(pattern, "$1,$2");
    return x;
}

有没有更简单或更优雅的方法?如果它也能与浮动一起工作,那就好了,但这不是必需的。它不需要特定于语言环境来决定句点和逗号

我建议使用phpjs.org的


我认为你的解决方案是我见过的较短的解决方案之一。我不认为有任何标准的JavaScript函数可以做这类事情,所以你可能只能靠自己了

我检查了css3规范,看看是否可以在CSS中实现这一点,但除非您希望每个数字都有自己的
,否则我认为这是不可能的

我确实发现了一个看起来很有前途的项目:。我没有使用过它,但是它看起来非常灵活,并且使用了单元测试。开发者也有很多关于这个主题的帖子(虽然很老)


请务必考虑国际用户:许多国家使用空间作为分隔符,并使用逗号从小数的整数部分中分离小数。 我使用了克里回答中的想法,但将其简化了,因为我只是想为我的特定目的寻找一些简单的东西。以下是我所做的:

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
带逗号的函数编号(x){
返回x.toString().replace(/\B(?${result}`);
回程通行证;
}
设故障=0;
失败+=!测试(0,“0”);
失败+=!测试(100,“100”);
失败+=!测试(1000,“1000”);
失败+=!测试(10000,“10000”);
失败+=!测试(100000,“100000”);
失败+=!测试(1000000,“1000000”);
失败+=!测试(10000000,“10000000”);
如果(失败){
log(`${failures}测试失败`);
}否则{
console.log(“所有测试通过”);
}
。作为控制台包装器{
最大高度:100%!重要;

}
这里有一个简单的函数,它为千个分隔符插入逗号。它使用数组函数而不是正则表达式

/**
 * Format a number as a string with commas separating the thousands.
 * @param num - The number to be formatted (e.g. 10000)
 * @return A string representing the formatted number (e.g. "10,000")
 */
var formatNumber = function(num) {
    var array = num.toString().split('');
    var index = -3;
    while (array.length + index > 0) {
        array.splice(index, 0, ',');
        // Decrement by 4 since we just added another unit to the array.
        index -= 4;
    }
    return array.join('');
};

代码沙盒链接和示例:

这是@mikez302答案的一个变体,但经过修改以支持带小数的数字(根据@neu rah的反馈,数字使用逗号(12345.6789)->“12345.6789”而不是“12345.6789”


感谢大家的回复。我根据一些答案构建了一个更“一刀切”的解决方案

第一个代码段添加了一个函数,该函数模仿到数字原型。如果我正在格式化一个数字,我通常需要小数位数,因此函数会采用小数位数来显示。一些国家使用逗号作为小数点,小数作为千位分隔符,因此函数允许设置这些分隔符

Number.prototype.numberFormat = function(decimals, dec_point, thousands_sep) {
    dec_point = typeof dec_point !== 'undefined' ? dec_point : '.';
    thousands_sep = typeof thousands_sep !== 'undefined' ? thousands_sep : ',';

    var parts = this.toFixed(decimals).split('.');
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousands_sep);

    return parts.join(dec_point);
}
您将按如下方式使用此选项:

var foo = 5000;
console.log(foo.numberFormat(2)); // us format: 5,000.00
console.log(foo.numberFormat(2, ',', '.')); // european format: 5.000,00
var foo = 5000;
var fooString = foo.numberFormat(2); // The string 5,000.00
var fooFloat = fooString.getFloat(); // The number 5000;

console.log((fooString.getFloat() + 1).numberFormat(2)); // The string 5,001.00
我发现我经常需要为数学运算返回数字,但是parseFloat将5000转换为5,只需取第一个整数值序列。因此,我创建了自己的浮点转换函数,并将其添加到字符串原型中

String.prototype.getFloat = function(dec_point, thousands_sep) {
    dec_point = typeof dec_point !== 'undefined' ? dec_point : '.';
    thousands_sep = typeof thousands_sep !== 'undefined' ? thousands_sep : ',';

    var parts = this.split(dec_point);
    var re = new RegExp("[" + thousands_sep + "]");
    parts[0] = parts[0].replace(re, '');

    return parseFloat(parts.join(dec_point));
}
现在,您可以按如下方式使用这两个功能:

var foo = 5000;
console.log(foo.numberFormat(2)); // us format: 5,000.00
console.log(foo.numberFormat(2, ',', '.')); // european format: 5.000,00
var foo = 5000;
var fooString = foo.numberFormat(2); // The string 5,000.00
var fooFloat = fooString.getFloat(); // The number 5000;

console.log((fooString.getFloat() + 1).numberFormat(2)); // The string 5,001.00

我将tofixed添加到Aki143S的解决方案中。 此解决方案使用点表示数千个分隔符,使用逗号表示精度

function formatNumber( num, fixed ) { 
    var decimalPart;

    var array = Math.floor(num).toString().split('');
    var index = -3; 
    while ( array.length + index > 0 ) { 
        array.splice( index, 0, '.' );              
        index -= 4;
    }

    if(fixed > 0){
        decimalPart = num.toFixed(fixed).split(".")[1];
        return array.join('') + "," + decimalPart; 
    }
    return array.join(''); 
};
实例

formatNumber(17347, 0)  = 17.347
formatNumber(17347, 3)  = 17.347,000
formatNumber(1234563.4545, 3)  = 1.234.563,454

我认为该功能将处理与此问题相关的所有问题

function commaFormat(inputString) {
    inputString = inputString.toString();
    var decimalPart = "";
    if (inputString.indexOf('.') != -1) {
        //alert("decimal number");
        inputString = inputString.split(".");
        decimalPart = "." + inputString[1];
        inputString = inputString[0];
        //alert(inputString);
        //alert(decimalPart);

    }
    var outputString = "";
    var count = 0;
    for (var i = inputString.length - 1; i >= 0 && inputString.charAt(i) != '-'; i--) {
        //alert("inside for" + inputString.charAt(i) + "and count=" + count + " and outputString=" + outputString);
        if (count == 3) {
            outputString += ",";
            count = 0;
        }
        outputString += inputString.charAt(i);
        count++;
    }
    if (inputString.charAt(0) == '-') {
        outputString += "-";
    }
    //alert(outputString);
    //alert(outputString.split("").reverse().join(""));
    return outputString.split("").reverse().join("") + decimalPart;
}

我很惊讶没有人提到。 它是在JavaScript 1.5(1999年推出)中实现的,因此基本上在所有主要浏览器中都支持它

var n=34523453.345
n、 toLocaleString()
"34,523,453.345"
从v0.12开始,它还通过包含


如果您想要一些不同的东西,可能会很有趣。

以下代码使用字符扫描,因此没有正则表达式

function commafy( num){
  var parts = (''+(num<0?-num:num)).split("."), s=parts[0], L, i=L= s.length, o='';
  while(i--){ o = (i===0?'':((L-i)%3?'':',')) 
                  +s.charAt(i) +o }
  return (num<0?'-':'') + o + (parts[1] ? '.' + parts[1] : ''); 
}
函数commafy(num){

var parts=(“”+(num如果您正在处理大量货币值和格式设置,则可能需要添加处理大量边缘案例和本地化的tiny:

// Default usage:
accounting.formatMoney(12345678); // $12,345,678.00

// European formatting (custom symbol and separators), could also use options object as second param:
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99

// Negative values are formatted nicely, too:
accounting.formatMoney(-500000, "£ ", 0); // £ -500,000

// Simple `format` string allows control of symbol position [%v = value, %s = symbol]:
accounting.formatMoney(5318008, { symbol: "GBP",  format: "%v %s" }); // 5,318,008.00 GBP

可以使用浏览器的
Intl
对象以国际友好方式插入千位分隔符:

Intl.NumberFormat().format(1234);
// returns "1,234" if the user's locale is en_US, for example
有关更多信息,请参阅,您可以指定区域设置行为或用户的默认设置。这更简单,因为它考虑了本地差异;许多国家使用句点分隔数字,而逗号表示小数


Intl.NumberFormat还不能在所有浏览器中使用,但它可以在最新的Chrome、Opera和IE中使用。Firefox的下一个版本应该支持它。Webkit似乎没有实现的时间表。

另一种方法,支持小数、不同的分隔符和负片

var number_format = function(number, decimal_pos, decimal_sep, thousand_sep) {
    var ts      = ( thousand_sep == null ? ',' : thousand_sep )
        , ds    = ( decimal_sep  == null ? '.' : decimal_sep )
        , dp    = ( decimal_pos  == null ? 2   : decimal_pos )

        , n     = Math.floor(Math.abs(number)).toString()

        , i     = n.length % 3 
        , f     = ((number < 0) ? '-' : '') + n.substr(0, i)
    ;

    for(;i<n.length;i+=3) {
        if(i!=0) f+=ts;
        f+=n.substr(i,3);
    }

    if(dp > 0) 
        f += ds + parseFloat(number).toFixed(dp).split('.')[1]

    return f;
}
var number\u format=函数(数字、十进制位置、十进制sep、千位sep){
变量ts=(千禧年九月==null?',':千禧年九月)
,ds=(十进制sep==null?'。:十进制sep)
,dp=(十进制位置==null?2:十进制位置)
,n=Math.floor(Math.abs(number)).toString()
,i=n.长度%3
,f=((数字<0)?'-':'')+n.substr(0,i)
;
对于(;i 0)
f+=ds+parseFloat(number).toFixed(dp).split('.')[1]
返回f;
}

@Jignesh Sanghani的一些更正,别忘了更新他的评论。

我在无意中读到这篇文章之前写了这篇文章。没有正则表达式,你可以真正理解代码

function formatNumber (num) {
    return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
}

print(formatNumber(2665));      // 2,665
print(formatNumber(102665));    // 102,665
print(formatNumber(111102665)); // 111,102,665
$(函数(){
函数插入命令{
//提前准备好东西
var d=s.indexOf('.');
var s2=d==-1?s:s切片(0,d);
//从右起每隔3位插入逗号
对于(变量i=s2.length-3;i>0;i-=3)
s2=s2.slice(0,i)+','+s2.slice(i);
//附加小数部分
如果(d!=-1)
s2+=s.slice(d);
返回s2;
}
$(“#学生会”).text(插入命令('1234567.89012');
});

让我试着改进一下,也许可以帮助别人
/\B(?=(\d{3})+\b)/g

"123456".replace(/\B(?=(\d{3})+\b)/g, ",")
var number = 1234567890; // Example number to be converted
// default behaviour on a machine with a local that uses commas for numbers
number.toLocaleString(); // "1,234,567,890"

// With custom settings, forcing a "US" locale to guarantee commas in output
var number2 = 1234.56789; // floating point example
number2.toLocaleString('en-US', {maximumFractionDigits:2}) // "1,234.57"
var nf = new Intl.NumberFormat();
nf.format(number); // "1,234,567,890"
var formatNumber = function (number) {
  var splitNum;
  number = Math.abs(number);
  number = number.toFixed(2);
  splitNum = number.split('.');
  splitNum[0] = splitNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  return splitNum.join(".");
}
var number = -123123231232;
formatNumber(number)
var number = 123123231232;
    number.toLocaleString()
var number = 3500;

console.log(new Intl.NumberFormat().format(number));
// → '3,500' if in US English locale
var nf = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
});
nf.format(123456.789); // ‘$123,456.79’
function toCommas(value) {
    return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
console.log(toCommas(123456789)); // 123,456,789

console.log(toCommas(1234567890)); // 1,234,567,890
console.log(toCommas(1234)); // 1,234
var number = 123456.789;

// request a currency format
console.log(number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }));
// → 123.456,79 €

// the Japanese yen doesn't use a minor unit
console.log(number.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }))
// → ¥123,457

// limit to three significant digits
console.log(number.toLocaleString('en-IN', { maximumSignificantDigits: 3 }));
// → 1,23,000
var number = 123456.789;

console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
// expected output: "123.456,79 €"

// the Japanese yen doesn't use a minor unit
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));
// expected output: "¥123,457"

// limit to three significant digits
console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number));

// expected output: "1,23,000"
let amount =350256.95
var formatter = new Intl.NumberFormat('en-IN', {
  minimumFractionDigits: 2,
});

// Use it.

formatter.format(amount);
3,50,256.95
const strToNum = str => {

   //Find 1-3 digits followed by exactly 3 digits & a comma or end of string
   let regx = /(\d{1,3})(\d{3}(?:,|$))/;
   let currStr;

   do {
       currStr = (currStr || str.split(`.`)[0])
           .replace( regx, `$1,$2`)
   } while (currStr.match(regx)) //Stop when there's no match & null's returned

   return ( str.split(`.`)[1] ) ?
           currStr.concat(`.`, str.split(`.`)[1]) :
           currStr;

};

strToNum(`123`) // => 123
strToNum(`123456`) // => 123,456
strToNum(`-1234567.0987`) // => -1,234,567.0987
(-1234567.0987).toLocaleString();
new Date();
 resultNumber = new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(yourNumber); 
function $(dollarAmount)
{
    const locale = 'en-US';
    const options = { style: 'currency', currency: 'USD' };
    return Intl.NumberFormat(locale, options).format(dollarAmount);
}
function no$(dollarAmount)
{
    return $(dollarAmount).replace('$','');
}
function addCommas(number, minDecimalPlaces = 0, maxDecimalPlaces = Math.max(3,minDecimalPlaces))
{
    const options = {};
    options.maximumFractionDigits = maxDecimalPlaces;
    options.minimumFractionDigits = minDecimalPlaces;
    return Intl.NumberFormat('en-US',options).format(number);
}
n.toLocaleString()
Number(1000).toLocaleString('ES-es')
n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, Number(10000).toLocaleString().substring(2, 3))
Number(1000).toString().replace(/\B(?=(\d{3})+(?!\d))/g, Number(10000).toLocaleString().substring(2, 3))
let number   = 1234.567
let decimals = 2
let decpoint = '.' // Or Number(0.1).toLocaleString().substring(1, 2)
let thousand = ',' // Or Number(10000).toLocaleString().substring(2, 3)

let n = Math.abs(number).toFixed(decimals).split('.')
n[0] = n[0].split('').reverse().map((c, i, a) =>
  i > 0 && i < a.length && i % 3 == 0 ? c + thousand : c
).reverse().join('')
let final = (Math.sign(number) < 0 ? '-' : '') + n.join(decpoint)

console.log(final)
    var formatted = (x+'').replace(/(\..*)$|(\d)(?=(\d{3})+(?!\d))/g, (digit, fract) => fract || digit + ',');