0

I am creating an app which calculates nutrients of food based on a specific amount. The user fills in the amount of food they have consumed and the app calculates the nutrient values.

My source data has values with decimals, for example: 100g of strawberries have 6,5 carbs.

When I fill in 100g of strawberries (which is the same amount of grams as the source data) the app will output 6 instead of 6,5. So it seems like my calculations ignore everything that's behind the comma (",").

My code:

$con = mysqli_connect('localhost','root','','food');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con, "food");
$sql = "SELECT * FROM products WHERE id = '".$q."'";
$result = mysqli_query($con, $sql);

if ($result->num_rows > 0) {
    while($row = mysqli_fetch_array($result)) {
        $GLOBALS['name'] = $row['product'];
        $GLOBALS['kcal'] = $row['kcal'] / 100 * $GLOBALS['amount'];
        $GLOBALS['protein'] = $row['protein'] / 100 * $GLOBALS['amount'];       
        $GLOBALS['fat'] = $row['fat'] / 100 * $GLOBALS['amount'];       
        $GLOBALS['carbs'] = $row['carbs'] / 100 * $GLOBALS['amount'];
    }
} else {
    echo "Geen gegevens";
}

If I use number_format around the equation, the results will still be wrong (output will be 6).

What am I doing wrong?

Demo

Fill in the top two inputs:

Strawberries (Aardbeien)

100

Click "Voeg toe"

1 Answer 1

2

Maybe, you need use str_replace function? For example:

$GLOBALS['kcal'] = str_replace(',','.',$row['kcal']) / 100 * $GLOBALS['amount'];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.