1
0
Fork 0
mirror of https://github.com/koalyptus/TableFilter.git synced 2024-06-25 00:40:32 +02:00
TableFilter/src/number.js

31 lines
1 KiB
JavaScript
Raw Normal View History

2016-09-10 16:07:46 +02:00
import {isNumber} from './types';
2016-09-19 09:37:45 +02:00
// import {FORMATTED_NUMBER} from './const';
2016-09-10 16:07:46 +02:00
/**
* Returns a number for a formatted number
* @param {String} Formatted number
* @param {String} Format type, currently 'formatted-number' or
* 'formatted-number-eu'
* @return {Number} Unformatted number
*/
2016-09-19 09:37:45 +02:00
export const parse = (value, decimal = '.') => {
2016-09-10 16:07:46 +02:00
// Return the value as-is if it's already a number
if (isNumber(value)) {
return value;
}
// Build regex to strip out everything except digits, decimal point and
// minus sign
2016-09-19 09:37:45 +02:00
// let decimal = format !== FORMATTED_NUMBER ? ',' : '.';
2016-09-10 16:07:46 +02:00
let regex = new RegExp('[^0-9-' + decimal + ']', ['g']);
let unformatted = parseFloat(
('' + value)
.replace(/\((.*)\)/, '-$1') // replace bracketed values with negatives
.replace(regex, '') // strip out any cruft
.replace(decimal, '.') // make sure decimal point is standard
);
// This will fail silently
return !isNaN(unformatted) ? unformatted : 0;
}