Skip to content

Instantly share code, notes, and snippets.

@hynkle
Created April 27, 2012 20:23
Show Gist options
  • Select an option

  • Save hynkle/2512637 to your computer and use it in GitHub Desktop.

Select an option

Save hynkle/2512637 to your computer and use it in GitHub Desktop.
currency input validation
# Managing potentially messy input from a free-form text input that's supposed to represent currency.
#
# Acceptable:
# 1
# 12
# 123
# 1234
# 1234.56
# $1
# $12
# $123
# $1234
# $1234.56
# $1,234
# $1,234.56
# $1,234,567.89
# .12
# $.12
#
# Unacceptable:
# 12$
# $
# .1
# 12.3
# 12,34
# nine thousand dollars and one cent
def cents_from_messy_currency_string(str)
currency_format = /
\A
\s* # leading spaces are fine
\$? # optional dollar sign
\s* # spaces after the dollar sign are fine
(
(\.\d{2}) # .23
|
\d+(\.\d{2})? # 1234, 1234.56
|
\d{1,3}(,\d{3})+(\.\d{2})? # 1,000 123,000,000, 1,000.24
)
\s* # trailing spaces are fine
\Z
/x
return nil unless str =~ currency_format
sanitized = str.gsub /[^0-9.]/, ''
sanitized['.'] ? sanitized.sub('.', '').to_i : sanitized.to_i*100
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment