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

30 lines
999 B
JavaScript
Raw Normal View History

2016-09-10 16:07:46 +02:00
import {isNumber} from './types';
/**
2016-10-03 06:26:24 +02:00
* Takes a string, removes all formatting/cruft and returns the raw float value
2016-09-10 16:07:46 +02:00
* @param {String} Formatted number
2016-10-03 06:26:24 +02:00
* @param {String} Decimal type '.' or ','
2016-09-10 16:07:46 +02:00
* @return {Number} Unformatted number
2016-10-03 06:26:24 +02:00
*
* https://github.com/openexchangerates/accounting.js/blob/master/accounting.js
2016-09-10 16:07:46 +02:00
*/
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
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;
2017-05-25 05:51:44 +02:00
};