Add 'Decimal-Mark' Thousands Separators to a Number

How to print a number using commas as thousands separators

Locale unaware

'{:,}'.format(value)  # For Python ≥2.7
f'{value:,}' # For Python ≥3.6

Locale aware

import locale
locale.setlocale(locale.LC_ALL, '') # Use '' for auto, or force e.g. to 'en_US.UTF-8'

'{:n}'.format(value) # For Python ≥2.7
f'{value:n}' # For Python ≥3.6

Reference

Per Format Specification Mini-Language,

The ',' option signals the use of a comma for a thousands separator. For a locale aware separator, use the 'n' integer presentation type instead.

Add 'decimal-mark' thousands separators to a number

If you want to add a thousands separator, you can write:

>>> '{0:,}'.format(1000000)
'1,000,000'

But it only works in Python 2.7 and above.

See format string syntax.

In older versions, you can use locale.format():

>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'en_AU.utf8'
>>> locale.format('%d', 1000000, 1)
'1,000,000'

the added benefit of using locale.format() is that it will use your locale's thousands separator, e.g.

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'de_DE.utf-8')
'de_DE.utf-8'
>>> locale.format('%d', 1000000, 1)
'1.000.000'

Add a thousands separator with decimals

Try this

const formatNumber = (number) => {
const value = number + '';
const list = value.split('.');
const prefix = list[0].charAt(0) === '-' ? '-' : '';
let num = prefix ? list[0].slice(1) : list[0];
let result = '';
while (num.length > 3) {
result = `,${num.slice(-3)}${result}`;
num = num.slice(0, num.length - 3);
}
if (num) {
result = num + result;
}
return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`;
};

console.log(formatNumber(3253.55));
console.log(formatNumber(50000.20));

How to format a number with commas as thousands separators?

I used the idea from Kerry's answer, but simplified it since I was just looking for something simple for my specific purpose. Here is what I have:

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

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

function test(x, expect) {
const result = numberWithCommas(x);
const pass = result === expect;
console.log(`${pass ? "✓" : "ERROR ====>"} ${x} => ${result}`);
return pass;
}

let failures = 0;
failures += !test(0, "0");
failures += !test(100, "100");
failures += !test(1000, "1,000");
failures += !test(10000, "10,000");
failures += !test(100000, "100,000");
failures += !test(1000000, "1,000,000");
failures += !test(10000000, "10,000,000");
if (failures) {
console.log(`${failures} test(s) failed`);
} else {
console.log("All tests passed");
}
.as-console-wrapper {
max-height: 100% !important;
}

How to add thousand separator to numbers in pandas

When formatting a number with , you can just use '{:,}'.format:

n = 10000
print '{:,}'.format(n)
n = 1000.1
print '{:,}'.format(n)

In pandas, you can use the formatters parameter to to_html as discussed here.

num_format = lambda x: '{:,}'.format(x)
def build_formatters(df, format):
return {
column:format
for column, dtype in df.dtypes.items()
if dtype in [ np.dtype('int64'), np.dtype('float64') ]
}
formatters = build_formatters(data_frame, num_format)
data_frame.to_html(formatters=formatters)

Adding the thousands separator has actually been discussed quite a bit on stackoverflow. You can read here or here.

Format number in R with both comma thousands separator and specified decimals

format not formatC:

format(round(as.numeric(1000.64), 1), nsmall=1, big.mark=",")  # 1,000.6

Adding thousand separator while printing a number

If you only need to add comma as thousand separator and are using Python version 3.6 or greater:

print(f"{number:,g}")

This uses the formatted string literals style. The item in braces {0} is the object to be formatted as a string. The colon : states that output should be modified. The comma , states that a comma should be used as thousands separator and g is for general number. [1]

With older Python 3 versions, without the f-strings:

print("{0:,g}".format(number))

This uses the format-method of the str-objects [2]. The item in braces {0} is a place holder in string, the colon : says that stuff should be modified. The comma , states that a comma should be used as thousands separator and g is for general number [3]. The format-method of the string object is then called and the variable number is passed as an argument.

The 68,471,24,3 seems a bit odd to me. Is it just a typo?

Formatted string literals

Python 3 str.format()

Python 3 Format String Syntax



Related Topics



Leave a reply



Submit