Javascript Thousand Separator / string format

2019-01-01 15:46发布

问题:

Is there any function in Javascript for formatting number and strings ?

I am looking for a way for thousand separator for string or numbers... (Like String.Format In c#)

回答1:

Update (7 years later)

The reference cited in the original answer below was wrong. There is a built in function for this, which is exactly what kaiser suggests below: toLocaleString

So you can do:

(1234567.89).toLocaleString(\'en\')              // for numeric input
parseFloat(\"1234567.89\").toLocaleString(\'en\')  // for string input

The function implemented below works, too, but simply isn\'t necessary.

(I thought perhaps I\'d get lucky and find out that it was necessary back in 2010, but no. According to this more reliable reference, toLocaleString has been part of the standard since ECMAScript 3rd Edition [1999], which I believe means it would have been supported as far back as IE 5.5.)


Original Answer

According to this reference there isn\'t a built in function for adding commas to a number. But that page includes an example of how to code it yourself:

function addCommas(nStr) {
    nStr += \'\';
    var x = nStr.split(\'.\');
    var x1 = x[0];
    var x2 = x.length > 1 ? \'.\' + x[1] : \'\';
    var rgx = /(\\d+)(\\d{3})/;
    while (rgx.test(x1)) {
            x1 = x1.replace(rgx, \'$1\' + \',\' + \'$2\');
    }
    return x1 + x2;
}

Edit: To go the other way (convert string with commas to number), you could do something like this:

parseFloat(\"1,234,567.89\".replace(/,/g,\'\'))


回答2:

If is about localizing thousands separators, delimiters and decimal separators, go with the following:

// --> numObj.toLocaleString( [locales [, options] ] )
parseInt( number ).toLocaleString();

There are several options you can use (and even locales with fallbacks):

number = 123456.7089;

result  = parseInt( number ).toLocaleString() + \"<br>\";
result += number.toLocaleString( \'de-DE\' ) + \"<br>\";
result += number.toLocaleString( \'ar-EG\' ) + \"<br>\";
result += number.toLocaleString( \'ja-JP\', { 
  style           : \'currency\',
  currency        : \'JPY\',
  currencyDisplay : \'symbol\',
  useGrouping     : true
} ) + \"<br>\";
result += number.toLocaleString( [ \'jav\', \'en\' ], { 
  localeMatcher            : \'lookup\',
  style                    : \'decimal\',
  minimumIntegerDigits     : 2,
  minimumFractionDigits    : 2,
  maximumFractionDigits    : 3,
  minimumSignificantDigits : 2,
  maximumSignificantDigits : 3
} ) + \"<br>\";

var el = document.getElementById( \'result\' );
el.innerHTML = result;
<div id=\"result\"></div>

Details on the MDN info page.

Edit: Commentor @I like Serena adds the following:

To support browsers with a non-English locale where we still want English formatting, use value.toLocaleString(\'en\'). Also works for floating point.



回答3:

Attempting to handle this with a single regular expression (without callback) my current ability fails me for lack of a negative look-behind in Javascript... never the less here\'s another concise alternative that works in most general cases - accounting for any decimal point by ignoring matches where the index of the match appears after the index of a period.

const format = num => {
    const n = String(num),
          p = n.indexOf(\'.\')
    return n.replace(
        /\\d(?=(?:\\d{3})+(?:\\.|$))/g,
        (m, i) => p < 0 || i < p ? `${m},` : m
    )
}

[
    format(100),        // \"100\"
    format(1000),       // \"1,000\"
    format(1e10),       // \"10,000,000,000\"  
    format(1000.001001) // \"1,000.001001\"
]
    .forEach(n => console.log(n))

» Verbose regex explanation (regex101.com)

\"flow



回答4:

There\'s a nice jQuery number plugin: https://github.com/teamdf/jquery-number

It allows you to change any number in the format you like, with options for decimal digits and separator characters for decimal and thousand:

$.number(12345.4556, 2);          // -> 12,345.46
$.number(12345.4556, 3, \',\', \' \') // -> 12 345,456

You can use it inside input fields directly, which is nicer, using same options like above:

$(\"input\").number(true, 2);

Or you can apply to a whole set of DOM elements using selector:

$(\'span.number\').number(true, 2);


回答5:

// thousand separates a digit-only string using commas
// by element:  onkeyup = \"ThousandSeparate(this)\"
// by ID:       onkeyup = \"ThousandSeparate(\'txt1\',\'lbl1\')\"
function ThousandSeparate()
{
    if (arguments.length == 1)
    {
        var V = arguments[0].value;
        V = V.replace(/,/g,\'\');
        var R = new RegExp(\'(-?[0-9]+)([0-9]{3})\'); 
        while(R.test(V))
        {
            V = V.replace(R, \'$1,$2\');
        }
        arguments[0].value = V;
    }
    else  if ( arguments.length == 2)
    {
        var V = document.getElementById(arguments[0]).value;
        var R = new RegExp(\'(-?[0-9]+)([0-9]{3})\'); 
        while(R.test(V))
        {
            V = V.replace(R, \'$1,$2\');
        }
        document.getElementById(arguments[1]).innerHTML = V;
    }
    else return false;
}   


回答6:

You can use javascript. below are the code, it will only accept numeric and one dot

here is the javascript

<script >

            function FormatCurrency(ctrl) {
                //Check if arrow keys are pressed - we want to allow navigation around textbox using arrow keys
                if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
                    return;
                }

                var val = ctrl.value;

                val = val.replace(/,/g, \"\")
                ctrl.value = \"\";
                val += \'\';
                x = val.split(\'.\');
                x1 = x[0];
                x2 = x.length > 1 ? \'.\' + x[1] : \'\';

                var rgx = /(\\d+)(\\d{3})/;

                while (rgx.test(x1)) {
                    x1 = x1.replace(rgx, \'$1\' + \',\' + \'$2\');
                }

                ctrl.value = x1 + x2;
            }

            function CheckNumeric() {
                return event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 46;
            }

  </script>

HTML

<input type=\"text\" onkeypress=\"return CheckNumeric()\" onkeyup=\"FormatCurrency(this)\" />

DEMO JSFIDDLE



回答7:

var number = 35002343;

console.log(number.toLocaleString());

for the reference you can check here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString



回答8:

I use this:

function numberWithCommas(number) {
    return number.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");
}

source: link



回答9:

number = 123456.7089;
result = parseInt( number ).toLocaleString() + \"<br>\";
result = number.toLocaleString( \'pt-BR\' ) + \"<br>\";

var el = document.getElementById( \'result\' );
el.innerHTML = result;
<div id=\"result\"></div>


回答10:

PHP.js has a function to do this called number_format. If you are familiar with PHP it works exactly the same way.



回答11:

All you need to do is just really this:

123000.9123.toLocaleString()
//result will be \"123,000.912\"


回答12:

I did not like any of the answers here, so I created a function that worked for me. Just want to share in case anyone else finds it useful.

function getFormattedCurrency(num) {
    num = num.toFixed(2)
    var cents = (num - Math.floor(num)).toFixed(2);
    return Math.floor(num).toLocaleString() + \'.\' + cents.split(\'.\')[1];
}