rails convert string to number

后端 未结 2 2074
遥遥无期
遥遥无期 2021-02-02 05:51

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

2条回答
  •  不要未来只要你来
    2021-02-02 06:25

    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
    

提交回复
热议问题