Adjust the output number in a JavaScript BMI calculator to the nearest whole number when using the

Hey there, I'm currently working on a beginner project and could use some assistance. My project involves creating a basic BMI calculator using metric units, but I seem to be encountering issues with rounding numbers. Here is a snippet of my code:

var heightInput = document.querySelector(".height-input-field");
var weightInput = document.querySelector(".weight-input-field");
var calculateButton = document.querySelector(".calculate");
var result = document.querySelector(".result");
var statement = document.querySelector(".result-statement");
var BMI, height, weight;

function calculationFunction() {
    height = heightInput.value;
    weight = weightInput.value;
    BMI = weight / Math.pow(height,2);
    result.innerText = Math.round(BMI*100)/100;

    if (BMI < 18.5) {
        statement.innerText = "Underweight";
        document.getElementById('result-color').style.backgroundColor="yellow";
    } else if ((BMI > 18.5) && (BMI < 24.9)) {
        statement.innerText = "Normal weight";
        document.getElementById('result-color').style.backgroundColor="green";
    } else if ((BMI > 25) && (BMI < 29.9)) {
        statement.innerText = "Overweight";
        document.getElementById('result-color').style.backgroundColor="yellow";
    } else {
        statement.innerText = "Obesity";
        document.getElementById('result-color').style.backgroundColor="red";
    }
}

calculateButton.addEventListener("click", calculationFunction);



/*
BMI Categories:
Underweight = <18.5
Normal weight = 18.5–24.9
Overweight = 25–29.9
Obesity = BMI of 30 or greater
*/

When I run the code, the result shows as 0: actual "app"

If you can offer any guidance, it would be greatly appreciated. Thanks!

Answer №1

Your calculation of BMI is currently set up for kilograms and meters, resulting in a very low value that gets rounded down to zero using the Math.round function.

If you prefer to work with centimeters instead of meters, simply adjust your formula as follows:

BMI = weight (kg) / height (cm) / height (cm) * 10000

To implement this change in code, update your BMI calculation line to:

BMI = weight / height / height * 10000

Answer №2

The method used to calculate the BMI might need some adjustments, but what stands out more are areas where the code could be improved for better readability, understanding, and reusability.

There is a flaw in your code that incorrectly labels individuals with a BMI of 18.5 or between 24.9 and 25 as "obese". This error stems from how you assess the BMI variable against range intervals.
If BMI is not less than 18.5 (the first if statement), then automatically it is greater than or equal to 18.5; there's no need to check if it is greater than specifically 18.5. Similarly, if the second if condition doesn't match, it implies that BMI is equal to or greater than 24.9, rendering your third check ineffective in capturing values like 24.95 which fall within the overlooked range.

When comparing a value against interval limits, focus on just one boundary per interval:

if (BMI < 18.5) {
  ...
} else if (BMI < 24.9) {           
  ...
} else if (BMI < 29.9) {           
  ...
} else {                           
  ...
}

The function calculateFunction() relies on global variables (heightInput, weightInput, result, statement) making it tricky to ascertain the values involved in its computations. Moreover, it carries out document changes which remain concealed during function usage checks.

Addtionally, the function name lacks clarity regarding its purpose. Including "function" in the function title serves no informative value; instead, opt for a clearer descriptor like calculateBMI().

Restrict the function to BMI computation only, moving other tasks (collecting input data, displaying BMI results) to a separate function:

// Function for BMI calculation
function calculateBMI(height, weight) {
  // Implement correct formula here
  return weight / Math.pow(height, 2);
}

// Function for determining description and color based on BMI
function getBMIDescription(BMI) {
  // Calculate text and color based on BMI value
  if (BMI < 18.5) {
    return { description: 'Underweight', color: 'yellow' };
  } else if (BMI < 24.9) {
    return { description: 'Normal weight', color: 'green' };
  } else if (BMI < 29.9) {
    return { description: 'Overweight', color: 'yellow' };
  } else {
    return { description: 'Obesity', color: 'red' };
  }
}

// Function for interacting with the document
function computeBMIandDisplay(doc) {
  // Pass page document as an argument for clarity

  // Gather input data
  let height = doc.querySelector('.height-input-field').value;
  let weight = doc.querySelector('.weight-input-field').value;

  // Compute BMI and determine description and color
  let BMI = calculateBMI(height, weight);
  let { description, color } = getBMIDescription(BMI);

  // Display values on screen
  doc.querySelector('.result').innerText = BMI.toFixed(2);

  // Show description and associated color
  doc.querySelector('.result-statement').innerText = description;
  doc.getElementById('result-color').style.backgroundColor = color;
}


// Button click handler installation
document.querySelector('.calculate').addEventListener('click', () => computeBMIandDisplay(document));

Answer №3

Thank you for the advice, I appreciate it. After reviewing my mistakes, I have made some improvements to my code:

var heightInput = document.querySelector(".height-input-field");
var weightInput = document.querySelector(".weight-input-field");
var calculateButton = document.querySelector(".calculate");
var result = document.querySelector(".result");
var statement = document.querySelector(".result-statement");
var BMI, height, weight;

function performCalculation() {
    height = heightInput.value;
    weight = weightInput.value;
    BMI = weight / height / height * 10000;
    result.innerText = Math.round(BMI*100)/100;

    if (BMI < 18.5) {
        statement.innerText = "Underweight";
        document.getElementById('result-color').style.backgroundColor="yellow";
        document.getElementById('result-color').style.color="black";
    } else if ((BMI > 18.5) && (BMI < 24.9)) {
        statement.innerText = "Normal weight";
        document.getElementById('result-color').style.backgroundColor="green";
        document.getElementById('result-color').style.color="white";
    } else if ((BMI > 25) && (BMI < 29.9)) {
        statement.innerText = "Overweight";
        document.getElementById('result-color').style.backgroundColor="yellow";
        document.getElementById('result-color').style.color="black";
    } else {
        statement.innerText = "Obesity";
        document.getElementById('result-color').style.backgroundColor="red";
        document.getElementById('result-color').style.color="white";
    }
}

calculateButton.addEventListener("click", performCalculation);

You can check out the updated calculator here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

RouterContext Error: Invariant violation: Do not utilize <withRouter(App) /> in a context without a <Router> present

After wrapping my app with BrowserRouter and trying to export it as withRouter(App), I encountered the following error in the browser: 16 | return ( 17 | <RouterContext.Consumer> 18 | {context => { > 19 | invariant( | ^ ...

Mastering the A-Frame Game Loop: Tips for Separating Logic and Rendering

Currently, I am experimenting with A-Frame and my Quest 2 headset in order to create a simple VR game. One particular challenge I am facing is understanding how to separate logic from rendering and establish a proper game loop. After discovering this tutor ...

Guide to implementing server-side data loading in App.js using Next.js

Is there a way to fetch the layout data along with the page without adding it to every individual page? The issue I'm facing is that my layout component, loaded once on App.jsx, remains consistent throughout the session. However, due to SSRed page loa ...

Internet Explorer's support for the `<summary>` tag in HTML

Is there a method to enable the summary tag in Internet Explorer 11, such as using an external library? <details> <summary>Here is the summary.</summary> <p>Lorem ipsum dolor sit amet</p> </details> App ...

Create data structures in python, php, c#, go, c++, and java using a JavaScript/JSON object

I am looking for a way to reverse the output of the JSON.stringify function specifically for node.js. My goal is to generate code snippets for various programming languages by converting JavaScript structures into their native counterparts in python, PHP, ...

What is the most effective method for the server to communicate with a web client through message delivery?

If you have any links to articles related to this topic, please share them as I may not know the exact terminology to search for. I am interested in understanding how a web application can facilitate server-to-client communications. The internet was not o ...

Updating file extension name in ReactJS: A quick guide

Looking to modify a file name and extension within the react.js public folder. Changing index.html to index.php https://i.stack.imgur.com/zp1Ga.jpg ** ...

Error encountered during Jest snapshot testing: Attempting to destructure a non-iterable object which is invalid

I am currently facing an issue with my React codebase where I am attempting to create snapshot tests for a component. However, Jest is showing an error indicating that I am trying to destructure a non-iterable instance. Despite thoroughly reviewing the cod ...

Using jQuery to iterate through a JSON array and extract key/value pairs in a loop

I want to create a loop that can go through a JSON array and show the key along with its value. I found a post that seems similar to what I need, but I can't quite get the syntax right: jQuery 'each' loop with JSON array Another post I cam ...

Struggling to send information to the data layer on every page in Angular 9

Currently, I am in the process of integrating a GTM snippet into my Angular project. However, I have noticed that when the page is hard reloaded, it pushes data but does not do so during normal navigation. I have already added the GTM snippet provided by ...

Utilizing Angular's File Upload feature with Glyphicon icons

Has anyone tried to open a local file using bootstrap glyphicon? I found this example at https://jsfiddle.net/JeJenny/ZG9re/, but it doesn't seem to work. Does anyone have any ideas on how to make this approach work with images like glyphicon? main.h ...

One click wonder: Easily print any webpage content with just the click of a button!

For example, upon clicking the button on my webpage, I want the content of another page to be sent directly to a printer. The objective is to bypass the print dialog box and print preview that typically appears when using the browser's default printin ...

Uploading a CSV file in JSON format to Amazon S3 with Node.js

Within my nodejs server.js script, the following code snippet can be found: router.post('/submission', (req, res) => { let data_filtered = req.body.data }) Upon user submission of a csv file, I am successfully retrieving it on the backend. ...

Using JavaScript to assign function arguments based on arbitrary object values

I am facing a challenge with a collection of arbitrary functions and a method that takes a function name along with an object or array of parameters to call the respective function. The issue arises from the varying number of inputs in these functions, som ...

Is it possible to expand the CORS permissions to the routers directly from the app?

I have a couple of questions: Is it possible to just use cors() once in my server.js instead of having to call and use it in every router file? Can I simply require express once in my server.js without having to call it in all my router files? Currently, ...

Eliminate elements from an array using a specific key for filtering

My Array is called MainArray MainArray=[{ {First Name: "First Name"}, {Last Name: "Contact"}, {Last Name: "Contact"} ] I am trying to trim the key-value pair from this array like this: if (key == 'First Name') { del ...

What are the steps to import a .obj 3D model into Three.js?

After incorporating your advice, here is the revised code: var renderer = new THREE.WebGLRenderer( { alpha: true } ); renderer.setSize( window.innerWidth, window.innerHeight ); element.appendChild( renderer.domElement ); var loader = new THREE.OBJLoader( ...

Guide to resetting a CSS animation with pure JavaScript

My flexbox contains 4 images, each triggering an animation on hover. However, the animation stops if I hover over the same image again. I have tried various JavaScript solutions found online to restart the animation, but none seem to be working for me. S ...

Does anyone know of a JavaScript function that works similarly to clientX and clientY but for tooltips when the mouse moves?

When using plain JavaScript to create a function that moves a tooltip on mouse move, the function works the first time with clientX and clientY, but fails to work when repeated. What could be causing this issue with clientX and clientY? Any suggestions on ...

trigger the focusout event within the focusin event

I am attempting to trigger the focusout event within the focusin event because I need to access the previous value from the focusin event, but the focusout event is being triggered multiple times. $('tr #edituser').focusin(function(){ var ...