Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is minus (negative) zero equivalent to 0 in PHP?

Tags:

php

mysql

I have a very basic MySQL query that reads rows from a database table and adds or subtracts the row value to a PHP string defined as $total_balance.

For example;

$statement_details_query = mysqli_query($con,"SELECT transaction_nominal_code, SUM(transaction_debit) as TotalDebit, SUM(transaction_credit) as TotalCredit FROM accounts_transaction GROUP BY transaction_nominal_code") or die(mysql_error());

while($statement_details = mysqli_fetch_array( $statement_details_query )) {

$balance = $statement_details['TotalCredit'] - $statement_details['TotalDebit'];

$total_balance = $total_balance + $balance;

}

echo number_format($total_balance, 2, '.', ',');

My question is, what is the difference between -0 and 0?

like image 602
Michael LB Avatar asked Jul 06 '15 15:07

Michael LB


2 Answers

I just asked myself the same question and thought 0 === -0 is true:

-1

true

How to reproduce:

<?php

$sum = 1.0000001;
$val = 1.00;

$a = round($val - $sum,2);
var_dump($a, $a === 0);

float(-0)
bool(false)

like image 190
sPooKee Avatar answered Sep 23 '22 07:09

sPooKee


In PHP, there is no real difference:

Float:

php > $negZ = -0.0;
php > $posZ = +0.0;
php > var_dump($negZ == $posZ, $negZ === $posZ);
bool(true)
bool(true)

Int:

php > $negZ = -0;
php > $posZ = +0;
php > var_dump($negZ == $posZ, $negZ === $posZ);
bool(true)
bool(true)
like image 21
Marc B Avatar answered Sep 21 '22 07:09

Marc B