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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
.to_fis the right way.Example:
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_fwill 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. EgThe above
.to_fbehavior 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::Floatas Mark Rushakoff suggests, since it raises an error when it is not perfectly happy with converting the input string.