Skip to content
Advertisement

Remove comma and change string to float

I want to find “money” in a file and change the string to float , for example, I use regular expression to find “$33,326” and would like to change to [33326.0, “$”] (i.e., remove comma, $ sign and change to float). I wrote the following function but it gives me an error

JavaScript

Can you help me debug my code?

Advertisement

Answer

When you do

JavaScript

you are not modifying anything. You should store the result in some variable, like:

JavaScript

But to cast to float your number have to have a dot, not a comma, so you can do:

JavaScript

and then cast it to float and append to the list:

JavaScript

Note:

Something important you should know is that when you loop through a list, like

JavaScript

i is a copy of each element, so if you modify it, no changes will be done in the list new. To modify the list you can iterate over the indices:

JavaScript
Advertisement