Lad mig komme med et eksempel.
Data:
CREATE TABLE decfun (
id INTEGER NOT NULL,
x DECIMAL(12,2),
PRIMARY KEY(id)
);
INSERT INTO decfun VALUES(1, 0.10);
INSERT INTO decfun VALUES(2, 0.20);
INSERT INTO decfun VALUES(3, 0.30);
"normal" kode:
<?php
echo "Get data:\r\n";
$con = mysqli_connect('localhost', 'root', '', 'Test') or die(mysqli_connect_error());
$stmt = mysqli_prepare($con, 'SELECT id,x FROM decfun') or die(mysqli_error($con));
mysqli_stmt_execute($stmt) or die(mysqli_error($con));
$rs = mysqli_stmt_get_result($stmt);
$sum = 0;
while($row = mysqli_fetch_array($rs, MYSQLI_ASSOC)) {
$x = $row['x'];
echo $x . ' ' . gettype($row['x']) . "\r\n";
$sum += $x;
}
echo $sum . ' ' . gettype($sum) . "\r\n";
mysqli_stmt_close($stmt);
mysqli_close($con);
echo "Format data:\r\n";
echo $sum . "\r\n";
echo number_format($sum) . "\r\n";
echo number_format($sum, 2) . "\r\n";
echo number_format($sum, 2, '.', '') . "\r\n";
echo number_format($sum, 2, ',', '') . "\r\n";
?>
Output:
Get data:
0.10 string
0.20 string
0.30 string
0.6 double
Format data:
0.6
1
0.60
0.60
0,60
Bedre kode:
<?php
echo "Get data:\r\n";
$con = mysqli_connect('localhost', 'root', '', 'Test') or die(mysqli_connect_error());
$stmt = mysqli_prepare($con, 'SELECT id,x FROM decfun') or die(mysqli_error($con));
mysqli_stmt_execute($stmt) or die(mysqli_error($con));
$rs = mysqli_stmt_get_result($stmt);
$sum = '0.00';
while($row = mysqli_fetch_array($rs, MYSQLI_ASSOC)) {
$x = $row['x'];
echo $x . ' ' . gettype($row['x']) . "\r\n";
$sum = bcadd($sum, $x, 2);
}
echo $sum . ' ' . gettype($sum) . "\r\n";
mysqli_stmt_close($stmt);
mysqli_close($con);
echo "Format data:\r\n";
echo $sum . "\r\n";
echo str_replace('.', ',', $sum) . "\r\n";
?>
Output:
Get data:
0.10 string
0.20 string
0.30 string
0.60 string
Format data:
0.60
0,60