将逗号转换为定界符 [英] Convert comma to point as delimiter

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

问题描述

如何将用户输入的数字从11,5转换为11.5?

How can I convert user number input from something like 11,5 to 11.5?

我尝试了以下作为回调:

I have tried the following as callback:

before_validation :comma_to_delimiter

def comma_to_delimiter
  self.price.to_s.gsub(',', '.').to_f
end

但这不起作用。我希望用户能够输入他想用作分隔符的任何内容-当前,当用户使用逗号而不是点时,应用程序将引发错误。

But this doesn't work. I want the user to be able to type in whatever he wants as delimiter - currently, the app throws an error when the user uses a comma instead of a point.

推荐答案

您所做的可能不是最好的方法,因此也许有人可以用更好的方法回答。但是,要使您的生产线正常工作,您需要使其实际上保持更改。

What you're doing may not be the best way, so perhaps someone can answer with a better approach. But to get your line working you need to make it actually persist the change.

self.price.to_s.gsub(',', '.').to_f

只会返回更改,但不会随处可见

Will just return the change, but that doesn't go anywhere in a callback!

self.price = self.price.to_s.gsub(',', '.').to_f
# OR
self.price.to_s.gsub!(',', '.').to_f

将更改保留在对象中。

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

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