javascript parseFloat '500,000' returns 50

2019-01-14 00:52发布

问题:

How would it be a nice way of handling this?

I already thought on removing the comma and then parsing to float.

Do you know a better/cleaner way?

Thanks

回答1:

Nope. Remove the comma.



回答2:

parseFloat( theString.replace(/,/g,'') );


回答3:

I don't know why no one has suggested this expression-

parseFloat( theString.replace(/[^\d\.]/g,'') );

Removes any non-numeric characters except for periods. You don't need custom functions/loops for this either, that's just overkill.



回答4:

You can use the string replace method, but not in a one liner as a regexp allows.

while(str.indexOf(',')!=-1)str= str.replace(',','');
parseFloat(str);

Or to make a single expression without a regexp=

return parseFloat(str.split(',').join(''));

I'd use the regexp.



回答5:

I don't have enough reputation to add a comment, but for anyone wondering on the performance for regex vs split/join, here's a quick fiddle: https://jsfiddle.net/uh3mmgru/

var test = "1,123,214.19";

var t0 = performance.now();
for (var i = 0; i < 1000000; i++)
{
    var a = parseFloat(test.replace(/,/g,''));
}
var t1 = performance.now();
document.write('Regex took: ' + (t1 - t0) + ' ms');
document.write('<br>')

var t0 = performance.now();
for (var i = 0; i < 1000000; i++)
{
    var b = parseFloat(test.split(',').join(''));
}
var t1 = performance.now();
document.write('Split/join took: ' + (t1 - t0) + ' ms');

The results I get are (for 1 million loops each):

Regex: 263.335 ms
Split/join: 1035.875 ms

So I think its safe to say that regex is the way to go in this scenario



回答6:

Building on the idea from @kennebec, if you want to make sure that the commas are correct, and you don't want to replace commas, you could try something like this:

function myParse(num) {
  var n2 = num.split(",")
  out = 0
  for(var i = 0; i < n2.length; i++) {
    out *= 1000;
    out += parseFloat(n2[i])
  }
  return out
}
alert(myParse("1,432,85"));
// Returns 1432085, as the comma is misplaced.

It may not be as fast, but you wanted alternatives :)



回答7:

What about a simple function to solve most of the common problems?

function getValue(obj) {
  Value = parseFloat( $(obj).val().replace(/,/g,'') ).toFixed(2);
  return +Value;
}

The above function gets values from fields (using jQuery) assuming the entered values are numeric (I rather validate fields while user is entering data, so I know for sure field content is numeric).

In case of floating point values, if well formatted in the field, the function will return a float point value correctly.

This function is far from complete, but it quickly fix the "," (comma) issue for values entered as 1,234.56 or 1,234,567. It will return valid number as far the content is numeric.

The + (plus) sign in front of the variable Value in the return command is a "dirty trick" used in JavaScript to assure the variable content returned will be numeric.

it is easy to modify the function to other purposes, such as (for instance), convert strings to numeric values taking care of the "," (comma) issue:

function parseValue(str) {
  Value = parseFloat( str.replace(/,/g,'') ).toFixed(2);
  return +Value;
}

Both operations can even be combined in one function. I.e.:

function parseNumber(item,isField=false) {
  Value = (isField) ? parseFloat( $(item).val().replace(/,/g,'') ).toFixed(2) : parseFloat( item.replace(/,/g,'') ).toFixed(2)
  return +Value;
}

In such case, if function is called result = parseNumber('12,092.98'); it will parse the value as it is a String. But if called as result = parseNumber('#MyField', true); it will try to obtain the value from '#MyField'.

As I said before, such functions are far from complete, and can be expanded in many ways. One idea is to check the first character of the given parameter (string) and decide based on the string format where to obtain the value to be parsed (if 1st character is = '#' then it is an ID from a DOM object, otherwise, if it begins with a number, it must be a string to be parsed).

Try it... Happy coding.