Corey
Corey

Reputation: 2563

Ruby string to int/float conversion

So let's say I have a string, '$3,444.11'. How do I convert that to a float 3,444.11? I have a form field. The user can insert "3,444.11", "3444.11", or "$3,444.11" or "€3,444.11". What I need is 3,444.11 as a float. Will I have to resort to regex? Or, is there a function already that I'm overlooking?

Upvotes: 4

Views: 5679

Answers (1)

Nevir
Nevir

Reputation: 8101

I don't think there's anything in the standard library that does this for you. Here's a quick one-liner:

'$3,444.11'.gsub(/[^\d\.]/, '').to_f
# => 3444.11

However, you might want to take a look at the money gem for advanced processing of currency strings.

Upvotes: 14

Related Questions