且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

rails 将字符串转换为数字

更新时间:2023-02-03 07:53:56

.to_f 是正确的方法.

示例:

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?

添加:

如果您知道您的输入字符串是一个浮点数的字符串版本,例如10.2",那么 .to_f 是***/最简单的转换方式.

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.

如果您不确定字符串的内容,那么在字符串中没有任何数字的情况下,使用 .to_f 将给出 0.它也会根据您的输入字符串提供各种其他值.例如

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

上述 .to_f 行为可能正是您想要的,这取决于您的问题情况.

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

根据您在各种错误情况下想要做什么,您可以使用 Kernel::Float 作为 Mark Rushakoff 建议的那样,因为当它对转换输入字符串不满意时会引发错误.

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.