ffouquet42
ffouquet42

Reputation: 134

How remove comma in array of string to convert in array of float

I have an array of strings:

my_array = ["$8,579.06", "$166.37", "$0.226463", "$346.31", "$275.27"]

I want to get a new array:

my_array = [8,579.06, 166.37, 0.226463, 346.31, 275.27]

I want to remove the $ and convert the values into floats, so I did this:

my_array.map! { |v| v.delete_prefix("$").to_f}

But that returned:

my_array = [8.0, 166.37, 0.226463, 346.31, 275.27]

I think it's because of the comma but my array is huge. How do I remove all the commas of each value without removing the ones separating the different indexes in my array?

Upvotes: 0

Views: 670

Answers (2)

the Tin Man
the Tin Man

Reputation: 160601

I'd do this:

ary = ["$8,579.06", "$166.37", "$0.226463", "$346.31", "$275.27"]
ary.map { |i| i.delete('$,').to_f }
# => [8579.06, 166.37, 0.226463, 346.31, 275.27]

delete is the magic part. It strips any characters named in the parameter from the string.

Commas in the viewable/screen display of numbers to denote thousands are a human artifice, to make it easier for us to gauge the magnitude of the number. Computers don't need them.

Assign the returned value from map to a variable or chain to it.

And, as a heads-up, be aware that different regions around the world use two different ways to denote thousands and the decimal point. Some use 1,000.00 and some are 1.000,00. Assuming that a string representation of currency has commas for thousands and a period for the fractional part is the source of a bug, quite a major bug if you're dealing with money, especially if you're doing financial calculations for loans. In your example you could write code to determine the values are U.S. based because of $, but without that you'd have a harder time telling. So if this is something you anticipate having to do I'd strongly recommend researching the problems and solutions.

Upvotes: 2

Sebastián Palma
Sebastián Palma

Reputation: 33470

I think this goes according to the docs:

... Extraneous characters past the end of a valid number are ignored...

You're getting just "8.0" because all the remaining characters after the 8 are ignored, as the comma can not be interpreted as a floating-point number. Which would be the same that doing "8".to_f and gives 8.0.

To avoid that you can try removing the commas per element inside the array:

["$8,579.06", "$166.37", "$0.226463", "$346.31", "$275.27"].map { |e| e.delete_prefix("$").delete(',').to_f }
# [8579.06, 166.37, 0.226463, 346.31, 275.27]

Upvotes: 3

Related Questions