How to Convert a String to a Number If It Has Commas in It as Thousands Separators

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



Leave a reply



Submit