javascript parseFloat '500,000' returns 500 when I need 500000

前端 未结 7 1509
清酒与你
清酒与你 2020-11-30 05: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?

Th

7条回答
  •  隐瞒了意图╮
    2020-11-30 06:02

    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.

提交回复
热议问题