1 | import {isNumber} from './types';
|
2 |
|
3 | /**
|
4 | * Takes a string, removes all formatting/cruft and returns the raw float value
|
5 | * @param {String} Formatted number
|
6 | * @param {String} Decimal type '.' or ','
|
7 | * @return {Number} Unformatted number
|
8 | *
|
9 | * https://github.com/openexchangerates/accounting.js/blob/master/accounting.js
|
10 | */
|
11 | export const parse = (value, decimal = '.') => {
|
12 | // Return the value as-is if it's already a number
|
13 | if (isNumber(value)) {
|
14 | return value;
|
15 | }
|
16 |
|
17 | // Build regex to strip out everything except digits, decimal point and
|
18 | // minus sign
|
19 | let regex = new RegExp('[^0-9-' + decimal + ']', ['g']);
|
20 | let unformatted = parseFloat(
|
21 | ('' + value)
|
22 | // replace bracketed values with negatives
|
23 | .replace(/\((.*)\)/, '-$1')
|
24 | // strip out any cruft
|
25 | .replace(regex, '')
|
26 | // make sure decimal point is standard
|
27 | .replace(decimal, '.')
|
28 | );
|
29 |
|
30 | // This will fail silently
|
31 | return !isNaN(unformatted) ? unformatted : 0;
|
32 | };
|