Created
February 26, 2019 23:13
-
-
Save zzidante/8c793f2c02f7574706f586e9380f293e to your computer and use it in GitHub Desktop.
Floatify_String ->Float or Nil
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
def floatify_string?(val) | |
# if its already a number type, return it | |
return val if (val.class == Integer || val.class == Float) | |
# pre-match zero so that we can initially weed out all no-numeric strings as unparseable | |
return 0.0 if val == "0" || val == "0.0" | |
return nil if val.to_f == 0.0 # "Hello".to_f => 0.0 | |
# only match float-like looking values: "1.0" => 1.0, "1" => 1.0, "0.001" => 0.001, "01345345" => 1345345.0 | |
return val.to_f if val =~ /^[-+]?[0-9]*\.?[0-9]+$/ | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment