How to add, multiply and divide the jquery percentile?

jquery

function formatDollar(num) {
  var p = num.toFixed(2).split(".");
  return "$" + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
      return num == "-" ? acc : num + (i && !(i % 3) ? "," : "") + acc;
  }, "");
}

suppose my original number is

$391,610

I get 90
from some value I want to add 90 to this $391610
it will become

$391,61090

there is no way to add 90 into a string.
how does this explain
the time I show doesn"t have to be the quantile
, but it doesn"t work when I want to add numbers


separate the storage of 2 variables.

$391610 this is what you need to show, save as a variable A.
391610 this is your original number, saved as another variable B. Use this to do the operation, and then turn it into the variable A by the method of quantile.


use type conversion parseFloat (). The intercept is a string type by default, and needs to be converted to a numeric type using the display type in order to add, subtract, multiply and divide.


you can use parseInt or various methods in Number in es6 to transfer


has rewritten the effect. Friends who use it can learn from it and need to be optimized

.
  function formatDollar(n,b){
    var aa = function(m){return String(m).split('').reverse().join('');};
    var bb = parseInt(n.replace(/[^0-9]/ig,""))+parseInt(b);
    return "$"+aa(aa(bb).replace(/(\d{3})/g,'$1,').replace(/\,$/,''));
  }

  var val= "$910,610";
  var str = formatDollar(val,90);

  console.log(str); //:$910,700

optimize the above code and change the regular mechanism

  function formatDollar(n,b){
    var aa = String(parseInt(n.replace(/[^\d|.]/g,''))+parseInt(b));
    return "$"+aa.replace(/(\d)(?=(\d{3})+$)/ig,'$1,');
  }

  var val= "$910,610";
  var str = formatDollar(val,90);

  console.log(str); //:$910,700

the following optimization can be done with a decimal point. I feel that this code has yet to be optimized

  function formatDollar(n,b){
    var aa = parseFloat(n.replace(/[^\d|.]/g,''))+parseFloat(b);
    var bb = String(aa).split(".");
    var cc = bb[0].replace(/(\d)(?=(\d{3})+$)/ig,'$1,');
    var dd = bb[1]?cc+"."+bb[1]:cc;
   
    return "$"+dd;
  }

  var val= "$910,610.15";
  var str = formatDollar(val,90.16);

  console.log(str); //:$910,700.31

optimize the above with decimal point. This should be regarded as the final version, no matter with or without decimal point.

  function formatDollar(n,b){
    var aa = parseFloat(n.replace(/[^\d|.]/g,''))+parseFloat(b);
    return "$"+aa.toLocaleString();
  }

  var val= "$910,610.15";
  var str = formatDollar(val,90.16);

  console.log(str); //:$910,700.31
Menu