Jump to content

[SOLVED] Problem with negative numbers


micmania1

Recommended Posts

Hi

 

Think what is happening is that php is using binary arithmatic, and a number ending .76 cannot be represented in binary. Suspect that a +ve and -ve version of the number land up represented with a very slightly different binary number.

 

All the best

 

Keith

Hi

 

Suspect not really avoidable short of writing custom functions for such calculations. It is a pretty common issue with computer systems that do not support decimal arithmatic (old mainframe langauges such as PL/1 and Cobol supported decimal formats to avoid issues like this).

 

If you really wanted to then you could process the number as an array of single digit decimal numbers and do all the addition / subtraction / multiplication / division a digit at a time.

 

All the best

 

Keith

function decimalAddition() {
$args = func_get_args();
$number = array();
$decimals = array();
foreach ($args as $v) {
	$exp = explode('.', $v);

	$number[] = $exp[0];
	if ($exp[0] < 0) {
		$decimals[] = 0 - $exp[1];
	} else {
		$decimals[] = $exp[1];
	}

}

if (!empty($number)) {
	$number = array_sum($number);
} else {
	$number = 0;
}

if (!empty($decimals)) {
	$decimals = array_sum($decimals) / 100;
} else {
	$decimals = 0;
}

return $number + $decimals;
}

 

Problem Solved.

 

Thanks for your time.

Don't use above code - its got bugs.

 

function decimalAddition() {
$args = func_get_args();

$number = array();
$decimals = array();
foreach ($args as $v) {
	$round = number_format($v, 0);

	$number[] = $round;
	$decimals[] = ($v - $round);
}

if (!empty($number)) {
	$number = array_sum($number);
} else {
	$number = 0;
}

if (!empty($decimals)) {
	$decimals = array_sum($decimals);
} else {
	$decimals = 0;
}

return $number + $decimals;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.