Domanda

I'm having an issue with number_format. When $val is over 1,000 in value, the $update will only SET a value of 1. If it is less than 1,00 in value, it will SET the correct value.

pmV is DECIMAL, 7,2.

I'm sure that I have just stared at this for too long and am missing something. What am I doing wrong? Please school me! ;)

// Set variables for received data
$id = strval($_GET['id']); // value is 1
$k = strval($_GET['k']); // value is 1
$dwt = strval($_GET['dwt']); // value is 25
$spot = "." . strval($_GET['spot']); // value is .70

//Query the database based on the variables received and 'echo' the results back
$sql="SELECT * FROM metals WHERE id = '".$id."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
    if ($id == 1){ // If we are calculating Gold, then add Karat into the calculation
        $num = ((($row['value']/20)*$k)*$dwt)*$spot;  //$row['value']=1200.01
    }
    else {  // If not, then don't
        $num = (($row['value']/20)*$dwt)*$spot;
    }
    $val = number_format($num,2,'.',',');
    echo $val;  // Send the value back to page --> Sending correct value - 1,050.01

    // Update the DB with the calculated PM amount
    $update="UPDATE totals SET pmV = $val WHERE id='1'";
    $result2 = mysqli_query($con,$update);  // UPDATES value of pmV to '1' instead of 1,050.01

    // Get the Diamond Value from the DB and Update the Total calculation
    $select="SELECT dV FROM totals WHERE id='1'";
    $result3 = mysqli_query($con,$select);
        while($dv = mysqli_fetch_array($result3)) {
            $val2 = $dv['dV']+$val;
            $sql4 = "UPDATE totals SET total = $val2 WHERE id='1'";
            $result4 = mysqli_query($con,$sql4);
            };
};

mysqli_close($con);
È stato utile?

Soluzione

1,050.01 is not a valid number. It's a formatted string. So when you try to treat it like a number, things break.

To round a number to teo decimal places, try this:

$val = floor($num*100)/100;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top