I have a list of prices with a comma for a decimal point and a dot as the thousand separator.
Some examples:
12,30
116,10
1.563,14
These come in this format from a third party. I want to convert them to floats and add them together.
What is the best way to do this? number_format doesn't seem to work with this format, and str_replace seems like overkill, as I have to do it more that once on each number.
Is there are better way? Thanks.
To convert number strings with commas in Python Pandas DataFrame to float, we can use the astype method. to convert the values in the data frame df 's colname column to a float by removing the commas from the strings with str. replace .
Click File > Options. On the Advanced tab, under Editing options, clear the Use system separators check box. Type new separators in the Decimal separator and Thousands separator boxes. Tip: When you want to use the system separators again, select the Use system separators check box.
go to Start > Control Panel > Regional and Language Options | Windows 10 (Start >type Control Panel and press enter > Region) Click Additional Settings. For Decimal Symbol, enter a dot: .
Using str_replace()
to remove the dots is not overkill.
$string_number = '1.512.523,55'; // NOTE: You don't really have to use floatval() here, it's just to prove that it's a legitimate float value. $number = floatval(str_replace(',', '.', str_replace('.', '', $string_number))); // At this point, $number is a "natural" float. print $number;
This is almost certainly the least CPU-intensive way you can do this, and odds are that even if you use some fancy function to do it, that this is what it does under the hood.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With