What’s the best way to convert a number that may contain dollar signs or
commas to a plain decimal? It seems like there would be a helper for
this, but I haven’t found one.
I could just declare this data invalid upon entry and make the user
re-enter the number, but the people using my software are older and
don’t seem to be breaking their habit of entering in numbers with
baggage. Any ideas?
What’s the best way to convert a number that may contain dollar
signs or
commas to a plain decimal?
newNumber = number.gsub(/[^\d.]/, ‘’)
Or use gsub!
All the other methods don’t account for stripping other garbage
characters that people/exports might toss into strings. like () or -
for negative nummbers.
Take the approach of extracting only what you want, not removing what
you don’t want.
“Balance: $ -(123,345.098) extra junk”.gsub(/[^\d.]/, ‘’)
I’ve figured out what my problem is. All of these methods work
(including the tr method which I previously thought didn’t). I’m just
having trouble implementing it with my form. I use the ‘enter_payment’
controller method to save the ‘event’ object from my form. I added line
3 to sanitize ‘amount’ before saving the event.
I’m guessing the the invalid ‘amount’ field is being set to zero when I
pass the event parameter to ‘enter_payment’? If so, how can I sanitize
before this? Thanks again for everyone’s help with this
I’m guessing the the invalid ‘amount’ field is being set to zero
when I
pass the event parameter to ‘enter_payment’? If so, how can I sanitize
before this? Thanks again for everyone’s help with this
You can get the entered value directly via params[:event][:amount]
So for instance,
3. payment.amount = params[:event][:amount].gsub(/[^\d.]/, ‘’)