Last active
January 3, 2016 05:49
-
-
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
This file contains 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
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