Reputation: 67
I have some forms on my site where after a user enters currency values those inputs are put into a calculator.
The input needs to be either floats or integers but I want it so that if they enter '$200,000' or '200000' it will both result in '200000.0' after clicking submit. (sort of the opposite of number_to_currency)
I was thinking something like
text = text.gsub(/[$,]/, '').to_f
or better yet take out all non digit characters but this will result in an unintentional zero in the output.
I also would like to format the result in the view so that if the resulting float has nothing after the decimal eg 200.00 then it will round up to 200. Otherwise it will round to 2 decimal place
Most preferably I would like it to work like the presence validator before the form actually submits.
What's the best way to go about implementing this? I'm thinking there is something obvious I've missed.
Upvotes: 0
Views: 1037
Reputation: 9344
For the second part, you could do this:
# after converting text to a float
text.modulo(1) == 0 ? text.to_i : sprintf("%.2f", text)
For example, if text = 200000.0
, we get 200000
using the above.
On the other hand, if text = 200000.1
, we get 200000.10
using the above.
Upvotes: 1