---
layout: page
title: "JavaScript bcadd function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/bcadd:869
- /functions/view/bcadd
- /functions/view/869
- /functions/bcadd:869
- /functions/869
---
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's bcadd

{% codeblock bc/bcadd.js lang:js https://raw.github.com/kvz/phpjs/master/functions/bc/bcadd.js raw on github %}
function bcadd (left_operand, right_operand, scale) {
  // From: http://phpjs.org/functions
  // +   original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/)
  // -    depends on: _phpjs_shared_bc
  // *     example 1: bcadd(1, 2);
  // *     returns 1: 3
  //  @todo: implement these testcases
  //        bcscale(0);
  //
  //        bcmath.test.result('bcadd', 1, '3', bcadd("1", "2"));
  //        bcmath.test.result('bcadd', 2, '4.0000', bcadd("-1", "5", 4));
  //        bcmath.test.result('bcadd', 3, '8728932003911564969352217864684.00', bcadd("1928372132132819737213", "8728932001983192837219398127471", 2));
  //        bcmath.test.result('bcadd', 4, '3.357000', bcadd('1.123', '2.234', 6));
  var libbcmath = this._phpjs_shared_bc();

  var first, second, result;

  if (typeof scale === 'undefined') {
    scale = libbcmath.scale;
  }
  scale = ((scale < 0) ? 0 : scale);

  // create objects
  first = libbcmath.bc_init_num();
  second = libbcmath.bc_init_num();
  result = libbcmath.bc_init_num();

  first = libbcmath.php_str2num(left_operand.toString());
  second = libbcmath.php_str2num(right_operand.toString());


  result = libbcmath.bc_add(first, second, scale);

  if (result.n_scale > scale) {
    result.n_scale = scale;
  }

  return result.toString();
}
{% endcodeblock %}

 - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/bc/bcadd.js)

Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are 
the closest match to this hashtable-like data structure. 

Please also note that php.js offers community built functions and goes by the 
[McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online 
functions that are far from perfect, in the hopes to spark better contributions. 
Do you have one? Then please just: 

 - [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/bc/bcadd.js)

### Example 1
This code
{% codeblock lang:js example %}
bcadd(1, 2);
{% endcodeblock %}

Should return
{% codeblock lang:js returns %}
3
{% endcodeblock %}


### Other PHP functions in the bc extension
{% render_partial _includes/custom/bc.html %}
