Skip to content

Instantly share code, notes, and snippets.

@zanona
Created November 10, 2012 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zanona/4051682 to your computer and use it in GitHub Desktop.
Save zanona/4051682 to your computer and use it in GitHub Desktop.
Parse any float number from within a provided text.

#parseFloats within text input#

Parse any float within a text by simply calling the method:

###Code:###

parseFloats('This was our 10th anniversary and I have spent $812,34 on a fancy dinner at the best 7th avenue restaurant.');

###Ouput:###

[ 10, 812.34, 7, min: 7, max: 812.34 ]

Use the convenience attributes min and max to retrieve the high and low values from the generated array. Works great for currencies ;)

function parseFloats(str) {
/*jslint regexp:true*/
str = (str || '').replace(/[\x80-\xFF]|&.{0,}?;/g, '') || '';
var m = str.match(/[0-9]{1,}(\.|,)?([0-9]{1,})?(\.|,)?([0-9]{1,})?/g) || [];
m = m.map(function (item) {
item = item.match(/(\d+)((,|\.)(?!.*(,|\.)[0-9]))?/g).join('').replace(/\.|,/, '.');
return parseFloat(item, 10);
});
m.min = Math.min.apply(Math, m);
m.max = Math.max.apply(Math, m);
return m;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment