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

33 lines
1 KiB
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 bracketed values with negatives
.replace(/\((.*)\)/, '-$1')
// strip out any cruft
.replace(regex, '')
// make sure decimal point is standard
.replace(decimal, '.')
2016-09-10 16:07:46 +02:00
);
// This will fail silently
return !isNaN(unformatted) ? unformatted : 0;
2017-05-25 05:51:44 +02:00
};