1.0.0 • Published 10 years ago
parse-num v1.0.0
parse-num
JavaScript component to parse, clean, remove formatting (unformat) numbers in strings.
Install
npm install --save parse-numUsage
parseNum
Signature: parseNum(value, [decimalSep])
Parameters:
value: Any value to parse a number from. If it'snullorundefined, it will returnNaN. If it's anumber, it will just return thenumber. Otherwise, it will coerce the inputvalueto astringusingtoString().decimalSep: optionalstringparameter to specify a decimal separator. Defaults to".".
Returns:
The parsed number.
Example:
const parseNum = require('parse-num')
// import parseNum from 'parse-num' // if using ES6
parseNum('$ 123,456.78') // => 123456.78
parseNum('$ 123,456') // => 123456
parseNum('&*()$ 123,456') // => 123456
parseNum(';$@#$%^&123,456.78') // => 123456.78
parseNum('$ -123,456') // => -123456
parseNum('$ -123,456.78') // => -123456.78
parseNum('&*()$ -123,456') // => -123456
parseNum(';$@#$%^&-123,456.78') // => -123456.78
parseNum('$ 123,456', ')') // => 123.456
parseNum('$ 123456|78', '|') // => 123456.78
parseNum('&*()$ 123>456', '>') // => 123.456
parseNum(';$@#$%^&123,456\'78', '\'') // => 123456.78Don't want NaN?
Don't ever want to deal with NaN? Do this:
var num = parseNum(null)
if (isNaN(num)) num = 0
// could also coerce to integer <=== BE careful, 'INTEGER', not 'FLOAT'
var num = ~~parseNum(null)
console.log(num) // => 0Credits
The basis of this code came from accounting.js.
License
MIT
1.0.0
10 years ago