polonium polonium - 1 year ago 109
PHP Question

PHP: Calculate with decimals

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: http://max-fit.nl/mealbuilder/

Fill in the top two inputs:

Strawberries (Aardbeien)


Click "Voeg toe"

Answer Source

Maybe, you need use str_replace function? For example:

$GLOBALS['kcal'] = str_replace(',','.',$row['kcal']) / 100 * $GLOBALS['amount'];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download