Teal Teal - 2 months ago 7
Javascript Question

How to Round to nearest integer in JavaScript

Hello I'm using JavaScript connected to my html code to make a conversion calculator. What I am having problems on is how to make my result into a rounded integer. I'm new to JavaScript and have tried many attempts to make Math.round(report1) or Math.round(report2) work into my code. Maybe I have to create a separate function? I'm stumped and would appreciate any help for this.

//displaing reported values...for kg to pounds
var report1 = function (kilogram, pound) {
document.getElementById("result").innerHTML =
kilogram + "kg = " + pound + "lb";
};


//displaing reported values...for pounds to kilograms
var report2 = function (pound, kilogram) {
document.getElementById("result").innerHTML =
pound + "lb = " + kilogram + "kg";
};

//reading in value from lb to kg button
document.getElementById("p_to_kg").onclick = function () {
var p = document.getElementById("weight").value;
report2(p, p_to_kg(p));
};

//formula for pounds to kilograms
function p_to_kg(pound_weight) {
return (pound_weight / 2.2);
}

//reading in value from kg to lb button
document.getElementById("kg_to_p").onclick = function () {
var kg = document.getElementById("weight").value;
report1(kg, kg_to_p(kg));
};

//formula for kilograms to pounds
function kg_to_p(kilogram_weight) {
return (2.2 * kilogram_weight);
}




This is my issue:

how to round this

Answer

HTML input values types are string so to calculate rounded value of them you should convert them to number. there is many ways to convert them to number like call the Number with the string value or adding a plus sign (+) (or division or multiply):

var val = document.querySelector('#val');
var k2l = document.querySelector('#kg-to-lb');
var l2k = document.querySelector('#lb-to-kg');
var res = document.querySelector('#result');

//displaing reported values...for kg to pounds
var report1 = function(kilogram, pound) {
  result.innerHTML =
    kilogram + "kg = " + pound + "lb";
};


//displaing reported values...for pounds to kilograms
var report2 = function(pound, kilogram) {
  result.innerHTML = pound + "lb = " + kilogram + "kg";
};

k2l.addEventListener('click', function(e) {
  var kilogram = val.value;
  var pound = Math.round(kilogram * 2.2);
  report1(kilogram, pound);
});
l2k.addEventListener('click', function(e) {
  var pound = val.value;
  var kilogram = Math.round(pound / 2.2);
  report2(pound, kilogram);
});
value
<input id="val" type="number" />

<button id="kg-to-lb">kg 2 lb</button>
<button id="lb-to-kg">lb 2 kg</button>
<div id="result"></div>