Good day to all,
Recently I have encountered a problem regarding to float numbers. I have this query that gets the values from database and insert it to an array. These values are decimal (float) numbers. Then basing on these values I have a given value inputted from a textfield, and this given value decrements(subt ract with the values from array) until its last remainder. Here's how it looks like:
So now, I know the script is ok.. but why 2.22044604925E-16 instead of zero? I hope someone can give me a clarification so I can revise to this one and prevent the float(2.2204460 4925E-16) to come out, but instead the 0.
Thanks. =)
Recently I have encountered a problem regarding to float numbers. I have this query that gets the values from database and insert it to an array. These values are decimal (float) numbers. Then basing on these values I have a given value inputted from a textfield, and this given value decrements(subt ract with the values from array) until its last remainder. Here's how it looks like:
Code:
//assume that these values are from query to array
$arr = array(0.2, 0.2, 1, 1, 1, 1, 1 ,1);
//now the given from textfield which creates error
$given = (float)2.4;
//this loop gets how many values should be needed
//I dont want to use the whole array values, so I need to check each value that is equal or near to the given value
$check_sum = 0;
$ctr = 0;
for ($a=0; $a<sizeof($arr); $a++) {
$check_sum = $check_sum + $arr[$a];
if ($check_sum<$given) {
$ctr++;
//if sum is less than the given continue on the loop
} else if ($check_sum==$given) {
$ctr++;
break;
// if the sum is equal then stop then loop
} else {
$ctr++;
break;
//as soon as the sum is already more than the given value then stop
}
//now i have figure out the length of my array to be use
for ($i=0; $i<$ctr; $i++) {
if ($given>$arr[$i]) {
$answer = $given - $arr[$i];
echo $given.' - '.$arr[$i].' = '.$answer.'<br />';
//decrements
$given = $given - $arr[$i];
} else if ($given == $arr[$i]) {
// if both equal, the loop ends, should display $answer = 0
echo $given.' - '.$arr[$i].' = '.$answer.'<br />';
} else {
//if given is less than the value from array, get the excess value
$excess = $arr[$i] - $given
echo $arr[$i].' - '.$given.' = '.$excess.'<br />';
}
}
//so the output should be
//2.4-0.2 = 2.2
//2.2-0.2 = 2
//2-1 = 1
//1-1 = 0
//but instead, it outputs like this
//2.4-0.2 = 2.2
//2.2-0.2 = 2
//2-1 = 1
//1-1 = 2.22044604925E-16
Thanks. =)
Comment