如何从浮点输入中去除逗号? [英] How to strip commas from float input?
问题描述
我有一个字段 -
:Revenue
它应该接受像 10,000.00
这样的值,但是如果我输入这样的值,它会将 10
存储到数据库而不是 10000.00
and it should accept values like 10,000.00
, but if I input such value it stores 10
into database instead of 10000.00
在保存之前我应该怎么做才能去掉逗号?
What should I do to strip of commas before I save?
我尝试在网上找到一些解决方案,但由于我发现它们不完整而无法实施.如果有人能帮助我,我将不胜感激.
I've tried to find a few solutions online but wasn't able to implement them as I found them incomplete. If someone could help me I would really appreciate it.
**我现在面临的问题是,一旦我输入值,rails 就会在运行 gsub 函数之前将字符串转换为浮点值,就像我输入 50,000.00 在调用 gsub 之前将其转换为浮点 50.0 一样,有什么办法可以覆盖 rails 在字符串上调用的 to_f 方法.
**The problem now I am facing is that as soon as I enter the value rails converts string in to float value before it can run the gsub function, like if I enter 50,000.00 its converting into float 50.0 before calling the gsub, is there any way to over the to_f method which rails is calling on the string.
推荐答案
删除逗号非常简单:
value.gsub(/,/, '').to_f
请记住,欧洲格式通常使用逗号作为十进制值分隔符,因此如果处理这些类型的数字,您的结果将相差 100 倍.
Keep in mind that European formatting often uses comma as the decimal value separator so your results would be off by a factor of 100 if processing those sorts of numbers.
这篇关于如何从浮点输入中去除逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!