How to convert a string to a number if it has commas in it as thousands separators?
import locale
locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )
locale.atoi('1,000,000')
# 1000000
locale.atof('1,000,000.53')
# 1000000.53
How can I parse a string with a comma thousand separator to a number?
Yes remove the commas:
let output = parseFloat("2,299.00".replace(/,/g, ''));
console.log(output);
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;
}
Python parse comma-separated number into int
>>> a = '1,000,000'
>>> int(a.replace(',', ''))
1000000
>>>
.NET String.Format() to add commas in thousands place for a number
String.Format("{0:n}", 1234); // Output: 1,234.00
String.Format("{0:n0}", 9876); // No digits after the decimal point. Output: 9,876
How to read data when some numbers contain commas as thousand separator?
I want to use R rather than pre-processing the data as it makes it easier when the data are revised. Following Shane's suggestion of using gsub
, I think this is about as neat as I can do:
x <- read.csv("file.csv",header=TRUE,colClasses="character")
col2cvt <- 15:41
x[,col2cvt] <- lapply(x[,col2cvt],function(x){as.numeric(gsub(",", "", x))})
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
Use Df Command to Show Only the %Used
Passing Variable from Python Script to Bash Script
Unicodedecodeerror, Invalid Continuation Byte
How to Print the Full Numpy Array, Without Truncation
What Does the Slash Mean in Help() Output
What Is the Reason for Performing a Double Fork When Creating a Daemon
Permutations Between Two Lists of Unequal Length
Iterate an Iterator by Chunks (Of N) in Python
Pip Install from Pypi Works, But from Testpypi Fails (Cannot Find Requirements)
Get Rows Based on Distinct Values from One Column
What Is the Correct Way to Include Localisation in Python Packages
How to Protect My Python Scripts on Raspberry Pi
And' (Boolean) VS '&' (Bitwise) - Why Difference in Behavior with Lists VS Numpy Arrays
Sorting a Python List by Two Fields
Tensorflow Not Found Using Pip
What Exactly Does the .Join() Method Do
How Does Swapping of Members in Tuples (A,B)=(B,A) Work Internally