phpday 2027 - Call for Papers

bcsub

(PHP 4, PHP 5, PHP 7, PHP 8)

bcsub — Sottrae un numero a precisione arbitraria da un altro

Descrizione

function bcsub(string $num1, string $num2, ?int $scale = null): string

Sottrae num2 da num1.

Elenco dei parametri

num1

L'operando di sinistra, come stringa.

num2

L'operando di destra, come stringa.

scale

Questo parametro viene utilizzato per impostare il numero di cifre dopo la virgola nel risultato. Se è null, verrà utilizzato il valore predefinito impostato con bcscale(), o in alternativa il valore della direttiva INI bcmath.scale.

Valori restituiti

Il risultato della sottrazione, come stringa.

Errori/Eccezioni

Questa funzione genera un'eccezione ValueError nei seguenti casi:

  • num1 o num2 non è una stringa numerica BCMath ben formata.
  • scale è al di fuori dell'intervallo valido.

Log delle modifiche

Versione Descrizione
8.0.0 scale ora è nullable.

Esempi

Example #1 Esempio di bcsub()

<?php

$a = '1.234';
$b = '5';

echo bcsub($a, $b);     // -3
echo bcsub($a, $b, 4);  // -3.7660

?>

Vedere anche:

+add a note

User Contributed Notes 2 notes

up
7
nd at snackbox dot org
8 years ago
The parameter order here is probably fairly obvious to most people (subtract right from left), but to clarify with a simple use case since I was struggling with this at the end of a long day:

<?php
echo bcsub('7', '5'); // 7 - 5 = '2'
echo bcsub('12', '17'); // 12 - 17 = '-5'
?>

Provide the parameters in the same order you would when using a normal subtraction operator.
up
0
charles dot adrian dot wood at gmail dot com
7 years ago
Please note that bcsub will fail in non-obvious ways if it's fed something that cannot be converted to a number. For instance:

bcsub('yes', 'no') === '0'

Yes, if you put garbage in, you get garbage out. Just don't expect bcsub to throw an error when you feed it an entirely non-numeric value.
To Top