PHPerKaigi 2025

BcMath\Number::add

(PHP 8 >= 8.4.0)

BcMath\Number::addAdds an arbitrary precision number

Descrição

public BcMath\Number::add(BcMath\Number|string|int $num, ?int $scale = null): BcMath\Number

Adds $this and num.

Parâmetros

num
The value to add.
scale
scale explicitly specified for calculation results. If null, the scale of the calculation result will be set automatically.

Valor Retornado

Returns the result of addition as a new BcMath\Number object.

When the BcMath\Number::scale of the result object is automatically set, the greater BcMath\Number::scale of the two numbers used for addition is used.

That is, if the BcMath\Number::scales of two values are 2 and 5 respectively, the BcMath\Number::scale of the result will be 5.

Erros/Exceções

This method throws a ValueError in the following cases:

  • num is string and not a well-formed BCMath numeric string
  • scale is outside the valid range

Exemplos

Exemplo #1 BcMath\Number::add() example when scale is not specified

<?php
$number
= new BcMath\Number('1.234');

$ret1 = $number->add(new BcMath\Number('2.34567'));
$ret2 = $number->add('-3.456');
$ret3 = $number->add(7);

var_dump($number, $ret1, $ret2, $ret3);
?>

O exemplo acima produzirá:

object(BcMath\Number)#1 (2) {
  ["value"]=>
  string(5) "1.234"
  ["scale"]=>
  int(3)
}
object(BcMath\Number)#3 (2) {
  ["value"]=>
  string(7) "3.57967"
  ["scale"]=>
  int(5)
}
object(BcMath\Number)#2 (2) {
  ["value"]=>
  string(6) "-2.222"
  ["scale"]=>
  int(3)
}
object(BcMath\Number)#4 (2) {
  ["value"]=>
  string(5) "8.234"
  ["scale"]=>
  int(3)
}

Exemplo #2 BcMath\Number::add() example of explicitly specifying scale

<?php
$number
= new BcMath\Number('1.234');

$ret1 = $number->add(new BcMath\Number('2.34567'), 1);
$ret2 = $number->add('-3.456', 10);
$ret3 = $number->add(7, 0);

var_dump($number, $ret1, $ret2, $ret3);
?>

O exemplo acima produzirá:

object(BcMath\Number)#1 (2) {
  ["value"]=>
  string(5) "1.234"
  ["scale"]=>
  int(3)
}
object(BcMath\Number)#3 (2) {
  ["value"]=>
  string(3) "3.5"
  ["scale"]=>
  int(1)
}
object(BcMath\Number)#2 (2) {
  ["value"]=>
  string(13) "-2.2220000000"
  ["scale"]=>
  int(10)
}
object(BcMath\Number)#4 (2) {
  ["value"]=>
  string(1) "8"
  ["scale"]=>
  int(0)
}

Veja Também

adicione uma nota

Notas Enviadas por Usuários (em inglês)

Não há notas de usuários para esta página.
To Top