4

I have a string str = "$ 9.0 / hr" or str = "$9.0/hr". I only want the integer value from this in this case 9.0

Language is Ruby 1.9.2

2
  • Will negative values ever show up? Do values less than 1.0 have a leading zero or not? Will the values ever use scientific notation? Commented Jan 24, 2012 at 16:58
  • 3
    Strictly, 9.0 isn't an integer; it's a float. Commented Jan 24, 2012 at 17:15

4 Answers 4

7

I'd use:

number = str[ /\d*(?:\.\d+)?/ ]

Or, if a leading 0 is required for values less than 1.0,

number = str[ /\d+(?:\.\d+)?/ ]

If you might have other numbers in the string, and only want the (first) one that has a dollar sign before it:

number = str[ /\$\s*(\d+(?:\.\d+)?)/, 1 ]

If it's guaranteed that there will (must) be a decimal place and digit(s) thereafter:

number = str[ /\$\s*(\d+\.\d+)/, 1 ]

Hopefully you can mix and match some of these solutions to get what you need.

Sign up to request clarification or add additional context in comments.

1 Comment

I used the second one ` str[ /\d+(?:\.\d+)?/ ]`. Thank you!
6

No regex :

str.delete("^0-9.")

Comments

4

If your prices always have dollars.cents format (which is likely for prices) then use this regex:

"$ 9.0 / hr".match(/\d+\.\d+/)[0] # => 9.0
"$9.0/hr".match(/\d+\.\d+/)[0] # => 9.0

Else you should take regex from Phrogz answer.

2 Comments

This requires the values to always have one decimal place; is that going to be true?
@Pgrogz, yes, this is possible for prices, let's see what answer fits better for Bhushan's case.
1

I don't know ruby, but the regex should be \d+(?:\.\d+)?. This will also work with "$9/hr"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.