Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a number with comma as decimal point to float

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.

like image 675
Aine Avatar asked Dec 01 '10 14:12

Aine


People also ask

How do you convert a number with a comma to float?

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 .

How do you use a comma as a decimal point in Excel?

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.

How do I change commas to dots in Excel Windows 10?

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: .


1 Answers

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.

like image 84
Teekin Avatar answered Oct 14 '22 04:10

Teekin