0

I want this:

'5.6535'.something => 56
'5.657'.something => 566
'5.3'.something => 530
'5'.something => 500

and so on...

My "string" float ranges from 1..9 and I want them to convert to an integer with three digets.

Thanks!

Kieran

6
  • 1
    What should the result be if the input is '56'? Commented Nov 11, 2011 at 22:03
  • Your string always contains only one digit before separator? Commented Nov 11, 2011 at 22:03
  • Do you want them to be rounded or just cut off at the end? Commented Nov 11, 2011 at 22:06
  • Yes that's right, it ranges from 1..9 so this should work. Commented Nov 11, 2011 at 22:27
  • Since when is "56" three digits long? Commented Nov 11, 2011 at 22:41

2 Answers 2

3
strings.each do |str|
  puts (str.to_f * 100).floor
end

Substitute round or ceil for floor depending on what behavior you want with rounding.

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

4 Comments

Thanks, it is really that simple! Found this as well: ruby-doc.org/core-1.9.3/String.html#method-i-to_f
This doesn't guarantee three digits.
@MarkByers, sure. question needs clarification if this matters.
@MarkByers Just edited the question. Thanks for pointing this out.
1
(x + '00­0').scan(/­\d/)[0,3].­join('').to_i

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.