Stripping Commas from Integers or Decimals in Rails

Stripping commas from Integers or decimals in rails

If your field is a Fixnum, it will never have commas, as Rails will have to convert the user input into a number in order to store it there.

However, it will do that by calling to_i on the input string, which is not what you want.
overriding the normal setter to something like

def price=(num)
num.gsub!(',','') if num.is_a?(String)
self[:price] = num.to_i
end

Not tested, but something resembling this should work...

You need to get at the commas while the input is still a string.

Edit:
As noted in comments, if you want to accept decimals, and create something not an integer, you need a different conversion than String.to_i. Also, different countries have different conventions for numeric punctuation, so this isn't a complete solution.

Rails strip all except numbers commas and decimal points

Try:

rate = rate.gsub(/[^0-9,\.]/, '')

Basically, you know the ^ means not when inside the character class brackets [] which you are using, and then you can just add the comma to the list. The decimal needs to be escaped with a backslash because in regular expressions they are a special character that means "match anything".

Also, be aware of whether you are using gsub or gsub!

gsub! has the bang, so it edits the instance of the string you're passing in, rather than returning another one.

So if using gsub! it would be:

rate.gsub!(/[^0-9,\.]/, '')

And rate would be altered.

If you do not want to alter the original variable, then you can use the version without the bang (and assign it to a different var):

cleaned_rate = rate.gsub!(/[^0-9,\.]/, '')

I'd just google for tutorials. I haven't used one. Regexes are a LOT of time and trial and error (and table-flipping).

This is a cool tool to use with a mini cheat-sheet on it for ruby that allows you to quickly edit and test your expression:

http://rubular.com/

Ruby (on Rails) Regex: removing thousands comma from numbers

result = inputstr.gsub(/,(?=\d{3}\b)/, '')

removes commas only if exactly three digits follow.

(?=...) is a lookahead assertion: It needs to be possible to be matched at the current position, but it's not becoming part of the text that is actually matched (and subsequently replaced).

Remove dollar sign and comma from price in form

I use ’$5,123’.gsub(/[^0-9\.]/, '') in my app for costs and quantities and it works fine for me!

Ruby on Rails - Currency : commas causing an issue

It might depend on what DBMS you're using, but as far as I know, decimal fields won't accept commas (at least not as separators; there might be a way to have the database accept a comma as a decimal point rather than a period). What you will have to do is remove the commas from your numbers (in a before_save or before_validation filter, perhaps), and then when you display the number, add the commas back in.

before_validation :strip_commas_from_non_labor_expense

def strip_commas_from_non_labor_expense
self.non_labor_expense = self.non_labor_expense.to_s.gsub(/,/, '').to_f
end

Then use number_to_currency when you want to display the expense amount formatted with comma separated groups and two decimal places, as you mentioned:

<%
non_labor_expense = ... # get value from your model
puts number_to_currency(non_labor_expense, :precision => 2, :separator => ',')
%>

How remove comma in array of string to convert in array of float

I'd do this:

ary = ["$8,579.06", "$166.37", "$0.226463", "$346.31", "$275.27"]
ary.map { |i| i.delete('$,').to_f }
# => [8579.06, 166.37, 0.226463, 346.31, 275.27]

delete is the magic part. It strips any characters named in the parameter from the string.

Commas in the viewable/screen display of numbers to denote thousands are a human artifice, to make it easier for us to gauge the magnitude of the number. Computers don't need them.

Assign the returned value from map to a variable or chain to it.

And, as a heads-up, be aware that different regions around the world use two different ways to denote thousands and the decimal point. Some use 1,000.00 and some are 1.000,00. Assuming that a string representation of currency has commas for thousands and a period for the fractional part is the source of a bug, quite a major bug if you're dealing with money, especially if you're doing financial calculations for loans. In your example you could write code to determine the values are U.S. based because of $, but without that you'd have a harder time telling. So if this is something you anticipate having to do I'd strongly recommend researching the problems and solutions.

Rails: Is there a rails trick to adding commas to large numbers?

You want the number_with_delimiter method. For example:

<%= number_with_delimiter(@number, :delimiter => ',') %>

Alternatively, you can use the number_with_precision method to ensure that the number is always displayed with two decimal places of precision:

<%= number_with_precision(@number, :precision => 2, :delimiter => ',') %>


Related Topics



Leave a reply



Submit