Ruby-on-rails rails 将字符串转换为数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2778093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:37:56  来源:igfitidea点击:

rails convert string to number

ruby-on-railsruby

提问by Yang

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

我想知道 Rails 中有什么方便的函数可以将带有负号的字符串转换为数字。例如-1005.32

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

当我使用该.to_f方法时,数字变为1005负号和小数部分被忽略。

回答by Larry K

.to_fis the right way.

.to_f是正确的方法。

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 knowthat 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.

如果您知道您的输入字符串是浮点数的字符串版本,例如“10.2”,那么 .to_f 是进行转换的最佳/最简单的方法。

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. Eg

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

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_fbehavior may be just what you want, it depends on your problem case.

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

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.

根据您在各种错误情况下要执行的操作,您可以Kernel::Float按照 Mark Rushakoff 的建议使用,因为当它对转换输入字符串不满意时会引发错误。

回答by Mark Rushakoff

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

您应该使用Kernel::Float来转换数字;在无效输入上,这将引发错误,而不仅仅是“尝试”转换它。

>> "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