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

前端 未结 7 1503
清酒与你
清酒与你 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:15

    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 :)

提交回复
热议问题