55

I am wondering what is a convenient function in Rails to convert a string with a negative sign into a number. e.g. -1005.32

When I use the .to_f method, the number becomes 1005 with the negative sign and decimal part being ignored.

1
  • Are you storing the result in an int rather than a float? Commented May 6, 2010 at 2:51

2 Answers 2

77

.to_f is the right way.

Example:

irb(main):001:0> "-10".to_f
=> -10.0
irb(main):002:0> "-10.33".to_f
=> -10.33

Maybe your string does not include a regular "-" (dash)? Or is there a space between the dash and the first numeral?

Added:

If you know that your input string is a string version of a floating number, eg, "10.2", then .to_f is the best/simplest way to do the conversion.

If you're not sure of the string's content, then using .to_f will give 0 in the case where you don't have any numbers in the string. It will give various other values depending on your input string too. Eg

irb(main):001:0> "".to_f 
=> 0.0
irb(main):002:0> "hi!".to_f
=> 0.0
irb(main):003:0> "4 you!".to_f
=> 4.0

The above .to_f behavior may be just what you want, it depends on your problem case.

Depending on what you want to do in various error cases, you can use Kernel::Float as Mark Rushakoff suggests, since it raises an error when it is not perfectly happy with converting the input string.

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

2 Comments

Look at the other answer, "abcd".to_f === 0 unfortunately
" '11.0' " with this can we change to 11.0 using to_f
27

You should be using Kernel::Float to convert the number; on invalid input, this will raise an error instead of just "trying" to convert it.

>> "10.5".to_f
=> 10.5
>> "asdf".to_f # do you *really* want a zero for this?
=> 0.0
>> Float("asdf")
ArgumentError: invalid value for Float(): "asdf"
    from (irb):11:in `Float'
    from (irb):11
>> Float("10.5")
=> 10.5

2 Comments

One of the nice things about Float() as opposed to Integer is that the former doesn't convert 010 to 8 (Integer regards something starting with 0 as octal)
@AndrewGrimm Or you could just pass the correct base in as the second argument: Integer("010", 10) #=> 10 (See Kernel#integer)

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.