Skip to content

Instantly share code, notes, and snippets.

@jclement
Last active January 3, 2016 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jclement/8418937 to your computer and use it in GitHub Desktop.
Save jclement/8418937 to your computer and use it in GitHub Desktop.
Safer parse float function that handles commas in input and bails outright if there is text in the input
parseFloatSafe: function(v) {
// A more sane parseFloat function
// - Verifies number in a sensible format and returns NaN otherwise. Sensible format = (#,000.##..) or (#.##) or (#,000) or (#)
// - supports scientific notation (E[-+]?###)
// - null / empty string return null
// - non-string types are converted to string and parsed that way
if (v === null) {return null;}
var tmp = ('' + v).trim();
if (tmp === '') {return null;}
if (tmp.match('^[-+]{0,1}[0-9]+([,]{0,1}[0-9]{3}){0,4}([.][0-9]+){0,1}([eE][-+]{0,1}[0-9]+){0,1}$')) {
return parseFloat(tmp.replace(/,/g, ''));
} else {
return NaN;
}
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment