-1

I searched for a while for a ruby or rails method that I can call to convert a simple string like 1,000.53 into a float value but I couldn't.

All I could see is number_to_human which does the reverse of what I want. Is there anything available for my use case or am I alone (which I dont think). Also all I want is a simple conversion as above with commas and dot. No fancy currency or other any other notation conversion needed.

Thanks

EDIT

'1,000.5'.gsub(/,/, '').to_f works but I am looking for an already available method in ruby or rails. Or a better alternative to my solution with gsub.

shankardevy
  • 4,290
  • 5
  • 32
  • 49
  • You can do to_f method to convert a string to a float number. But in this case the string contains a comma character, so you have to delete it first. str = "1,000.53" str.delete(",").to_f This will give you the proper float number. – Abhilash M A Oct 25 '14 at 05:43
  • I don't know how this question was marked as repeated. a) The question that it points only handles numbers on an english locale b) The solution provided would now match things that are not numbers into numbers – Alex Recuenco Aug 29 '23 at 09:46

2 Answers2

13

First, remove all chars from the string that are not a digit or the separator (. in your example). Then call to_f on the sanitized string:

'1,000.53'.gsub(/[^\d.]/, '').to_f #=> 1000.53
spickermann
  • 100,941
  • 9
  • 101
  • 131
-6

to_f might work

Try "your_string".to_f

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
Laura Gyre
  • 141
  • 8
  • nope. it wont. '1,000'.to_f #=> 1.0 – shankardevy Oct 25 '14 at 05:47
  • 3
    Welcome to SO, Laura. `'1,000.53'.to_f` would return 1.0 because of how the method does coercions. Hence the OP's question. You can always edit your answer, or delete it if it attracts too many downvotes. – Todd A. Jacobs Oct 25 '14 at 06:04