How to Print a Number Using Commas as Thousands Separators

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.

How to print a number with commas as thousands separators in JavaScript

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 print a number with commas as thousands separators in JavaScript

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 print a number with commas as thousands separators in JavaScript

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;
}

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

How to print a number with commas as thousands separators in Java..And I also want to print just 2 number after the point

NumberFormat currencyInstance = NumberFormat.getCurrencyInstance(Locale.US);
currencyInstance.setMaximumFractionDigits(0);
System.out.println(currencyInstance.format(12345679));

Output: $12,345,679

Pandas Series/Dataframe: Format string numbers with commas as Thousands Separators

Solution using apply lambda

import pandas as pd
import numpy as np

def format_float(x):
try:
flt = float(x)
return "{:,}".format(flt)
except:
return x

s = {'A': "Hello", 'B': "593753", 'C': "16.8|", "D" : np.nan, "E":"%"}
s = pd.Series(data=s, index=['A', 'B', 'C',"D","E"])

s2 = s.apply(lambda x: format_float(x))


Related Topics



Leave a reply



Submit