Skip to content

Instantly share code, notes, and snippets.

@benvds
Created January 7, 2017 11:54
Show Gist options
  • Save benvds/9f48b6bff7ae150ee350613509afaa86 to your computer and use it in GitHub Desktop.
Save benvds/9f48b6bff7ae150ee350613509afaa86 to your computer and use it in GitHub Desktop.
/**
* Returns a number from a given string. It ignores any characters, including
* comma's and points. When more than 1 number is found in a string, the last
* number is used as the fractional of the number. For example:
*
* '€ 12,34' => 12.34
* '1,234.567 %' => 1234.567
*
* @argument {string} text - text containing the number or number parts
* @returns {number|undefined} - parsed number or undefined when none found
*/
function parseNumber(text) {
var pattern = /\d+/gmi;
var numberParts = text.match(pattern) || [];
if (numberParts.length === 0) {
return undefined;
} else if (numberParts.length === 1) {
// add fractionals if numberParts only contains 1 number
numberParts.push('0');
}
var integers = Number.parseInt(numberParts.slice(0, -1).join(''));
var fractionals = Number.parseInt(numberParts.slice(-1)[0]);
return integers +
(fractionals / (Math.pow(10, fractionals.toString().length)));
}
console.clear();
var tests = [
{ in: '€ 12', out: 12 },
{ in: '€ 12,47', out: 12.47 },
{ in: '€ 12,00', out: 12 },
{ in: '€ 12,345', out: 12.345 },
{ in: '€ 0,35', out: 0.35 },
{ in: '€ 1.234,56', out: 1234.56 },
{ in: '€ 1.234.567,89', out: 1234567.89 },
{ in: '12', out: 12 },
{ in: '$ 12.47', out: 12.47 },
{ in: '$ 12.00', out: 12 },
{ in: '$ 0.35', out: 0.35 },
{ in: '$ 1,234.56', out: 1234.56 },
{ in: '$ 1,234,567.89', out: 1234567.89 },
{ in: '', out: undefined },
{ in: 's', out: undefined },
];
tests.forEach(function(test) {
var result = parseNumber(test.in);
console.log(result === test.out ? 'success' : 'fail');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment