How to strip commas from float input?

2020-04-18 06:44发布

问题:

I have a field -

:Revenue

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.

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

回答1:

Removing commas is pretty simple:

value.gsub(/,/, '').to_f

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.



回答2:

You can take a String#delete.

"10,000,000.00".delete(',').to_f 
# => 10000000.0


回答3:

I found the solution after looking at few places and combining few solutions, since I had to use gsub before the linking to model has to be done. so I created the method in my controller and called it before create and update action. and wrote the following code in the method

params[:record][:Revenue] = params[:record][:Revenue].gsub(/,/,"")