Created
April 27, 2012 20:23
-
-
Save hynkle/2512637 to your computer and use it in GitHub Desktop.
currency input validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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