@cityssm/string-to-numeric
v1.0.0
Published
Parses formatted numeric strings into numbers. Handles cases parseFloat() misses.
Downloads
102
Maintainers
Readme
String to Numeric
Parses formatted numeric strings into numbers. Handles cases parseFloat()
misses.
Helpful when importing formatted data.
Supports formatted numeric strings that are not supported by Javascript's
parseInt()
and parseFloat()
functions, including:
| Formatting | Example | Number.parseFloat()
| String to Numeric |
| ----------------------------------------------------------------------- | ---------------- | --------------------- | ----------------- |
| Numbers with thousands separators | "1,234.56"
| ❌ 1
| ✔️ 1234.56
|
| Numbers with surrounding brackets (common in accounting) | "(6000)"
| ❌ NaN
| ✔️ -6000
|
| Numbers with leading units | "$54.32"
| ❌ NaN
| ✔️ 54.32
|
| Numbers using a comma decimal separator (with optional parameter) | "1,23"
| ❌ 1
| ✔️ 1.23
|
| Combinations of formatting | "($65,432.10)"
| ❌ NaN
| ✔️ -65432.1
|
Installation
npm install @cityssm/string-to-numeric
Usage
import stringToNumeric from '@cityssm/string-to-numeric'
console.log(stringToNumeric('1,234.56'))
// => 1234.56
console.log(stringToNumeric('$54.32'))
// => 54.32
Note
The decimal separator will attempt to be detected based on the computer's settings.
If the computer's locale settings do not match the decimal separator in string being parsed,
set the decimalSeparator
option.
console.log(stringToNumeric('1,23', { decimalSeparator: ',' }))
// => 1.23