Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby string to int/float conversion

Tags:

ruby

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?

like image 316
Corey Avatar asked Dec 09 '22 18:12

Corey


1 Answers

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.

like image 94
Nevir Avatar answered Dec 19 '22 05:12

Nevir