Skip to content

Instantly share code, notes, and snippets.

@zzidante
Created February 26, 2019 23:13
Show Gist options
  • Save zzidante/8c793f2c02f7574706f586e9380f293e to your computer and use it in GitHub Desktop.
Save zzidante/8c793f2c02f7574706f586e9380f293e to your computer and use it in GitHub Desktop.
Floatify_String ->Float or Nil
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