rails 将字符串转换为数字 [英] rails convert string to number

查看:48
本文介绍了rails 将字符串转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

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

这篇关于rails 将字符串转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆