Incorrect Result in JavaScript Calculation

Incorrect result in JavaScript calculation

The value of an input is always a string, so + ends up being string concatenation ("10" + "10" is "1010", as opposed to 10 + 10 which is 20).

If you're using an input type="number" (the OP isn't, but others finding this answer may) and the browser supports them, you can use valueAsNumber instead:

var onerepmax = document.wodCalculate.oneRepMax.valueAsNumber;

If you're using type="text" or the browser doesn't support valueAsNumber:

You can convert user-input values using parseInt(value, 10) (the 10 = decimal, base 10) if they're meant to be whole numbers, e.g.:

var onerepmax = parseInt(document.wodCalculate.oneRepMax.value, 10);

That's just one option, though, you have several:

  • The unary + operator: value = +value will coerce the string to a number using the JavaScript engine's standard rules for that. The number can have a fractional portion (e.g., +"1.50" is 1.5). Any non-digits in the string (other than the e for scientific notation) make the result NaN. Also, +"" is 0, which may not be intuitive.

    var onerepmax = +document.wodCalculate.oneRepMax.value;
  • The Number function: value = Number(value). Does the same thing as +.

    var onerepmax = Number(document.wodCalculate.oneRepMax.value);
  • The parseInt function, usually with a radix (number base): value = parseInt(value, 10). The downside here is that parseInt converts any number it finds at the beginning of the string but ignores non-digits later in the string, so parseInt("100asdf", 10) is 100, not NaN. As the name implies, parseInt parses only a whole number.

    // (Same as the first one above)
    var onerepmax = parseInt(document.wodCalculate.oneRepMax.value, 10);
  • The parseFloat function: value = parseFloat(value). Allows fractional values, and always works in decimal (never octal or hex). Does the same thing parseInt does with garbage at the end of the string, parseFloat("123.34alksdjf") is 123.34.

    var onerepmax = parseFloat(document.wodCalculate.oneRepMax.value);

So, pick your tool to suit your use case. :-)

Calculator giving wrong results in JS

Here is the code working:

function soma(type){  var s1 = parseInt(document.getElementById("valor1").value,10);  var s2 = parseInt(document.getElementById("valor2").value,10);  document.getElementById("resultado").style.display = "block";  var result;
if (type === '+') { result = s1 + s2; } else if (type === '-') { result = s1 - s2; } else if(type === '*'){ result = s1 * s2; }else if(type === '/'){ result = s1 / s2; }
document.getElementById("resultado").innerHTML = result;}
<div class="container text-center">  <input name="Valor 1" id="valor1">  <input name="Valor 2" id="valor2"><br>  <button type="submit" onclick="soma('+')" id="btnSoma">Somar</button><br>  <button type="submit" onclick="soma('-')" id="btnSubtrair">Subtrair</button><br>  <button type="submit" onclick="soma('/')" id="btnDividir">Dividir</button><br>  <button type="submit" onclick="soma('*')" id="btnMultiplicar">Multiplicar</button><br>  <p id="resultado">Resultado</p></div>

Calculation of percentage giving wrong result

check this updated code

var data = [{"amount":518212,"billdate":"2018-08-04","outlet":"JAYANAGAR"},{"amount":104801,"billdate":"2018-08-04","outlet":"MALLESHWARAM"},{"amount":138151,"billdate":"2018-08-04","outlet":"KOLAR"},{"amount":628358,"billdate":"2018-08-05","outlet":"JAYANAGAR"},{"amount":115223,"billdate":"2018-08-05","outlet":"MALLESHWARAM"},{"amount":134107,"billdate":"2018-08-05","outlet":"KOLAR"},{"amount":177866,"billdate":"2018-08-06","outlet":"JAYANAGAR"},{"amount":66095,"billdate":"2018-08-06","outlet":"KOLAR"}]    /*var data = [  {    amount: 518212,    billdate: '2018-08-04',    outlet: 'JAYANAGAR',  },  {    amount: 104801,    billdate: '2018-08-04',    outlet: 'MALLESHWARAM',  },  {    amount: 138151,    billdate: '2018-08-04',    outlet: 'KOLAR',  },]*/
let formatData = function (data) { let billdates = []; let outlets = []; data.forEach(element => { if (billdates.indexOf(element.billdate) == -1) { billdates.push(element.billdate); } if (outlets.indexOf(element.outlet) == -1) { outlets.push(element.outlet); } }); return { data: data, billdates: billdates, outlets: outlets,
}; };
let renderTable = function (data) { billdates = data.billdates; outlets = data.outlets; data = data.data; let tbl = document.getElementById("tbl"); let table = document.createElement("table"); let thead = document.createElement("thead"); let headerRow = document.createElement("tr"); let th = document.createElement("th"); th.innerHTML = "Bill_____Date"; headerRow.appendChild(th); let grandTotal = 0; let outletWiseTotal = {}; th = document.createElement("th"); th.innerHTML = "Total1"; headerRow.appendChild(th); outlets.forEach(element => { th = document.createElement("th"); th.innerHTML = element;
headerRow.appendChild(th); outletWiseTotal[element] = 0; data.forEach(el => { if (el.outlet == element) { outletWiseTotal[element] += parseInt(el.amount); } }); grandTotal += outletWiseTotal[element]; }); thead.appendChild(headerRow); headerRow = document.createElement("tr"); th = document.createElement("th"); th.innerHTML = "Total"; headerRow.appendChild(th);
outlets.forEach(element => { th = document.createElement("th"); // console.log(outletWiseTotal[element]); var test = ((outletWiseTotal[element] / grandTotal) * 100);
var fix = test.toFixed(2) + "%"; console.log(fix) // this one is giving me right result for row "Total" th.innerHTML = fix; th.classList.add("text-right"); //ol wise total
headerRow.appendChild(th); }); th = document.createElement("th"); th.innerHTML = "100%" //grandTotal th.classList.add("text-right"); // grand total headerRow.insertBefore(th, headerRow.children[1]); thead.appendChild(headerRow); table.appendChild(thead);
let tbody = document.createElement("tbody"); billdates.forEach(element => { let row = document.createElement("tr"); td = document.createElement("td"); td.innerHTML = element; row.appendChild(td); let total = 0; outlets.forEach(outlet => { let el = 0; let tempTotal = 0; data.forEach(d => { if (d.billdate == element && d.outlet == outlet) { total += parseInt(d.amount); el = d.amount; } if (d.billdate == element){ tempTotal += parseInt(d.amount); } }); td.classList.add("text-right"); var test1 = ((el / tempTotal) * 100); console.log('(' + el + '/' + tempTotal + ')*100 == ' + test1) //this one is giving some wrong result for first column it is giving 100% which is wrong td = document.createElement("td"); td.innerHTML = el.toLocaleString('en-in'); row.appendChild(td); });
td = document.createElement("td"); td.innerHTML = total; //total date wise td.classList.add("text-right"); //console.log(total) // total date wise
row.insertBefore(td, row.children[1]); tbody.appendChild(row); });
table.appendChild(tbody); tbl.innerHTML = ""; tbl.appendChild(table); table.classList.add("table"); table.classList.add("table-striped"); table.classList.add("table-bordered"); } let formatedData = formatData(data); renderTable(formatedData);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script><div id="tbl"></div>

jQuery Math Formula Issue - Incorrect result or NaN

Change the following lines:

var Rn = $("input[id='Rn']").val()
var D = $("input[id='radius']").val()
var St = $("input[id='St']").val()
var Sn = $("input[id='Sn']").val()

to

var Rn = parseFloat($("input[id='Rn']").val());
var D = parseFloat($("input[id='radius']").val());
var St = parseFloat($("input[id='St']").val());
var Sn = parseFloat($("input[id='Sn']").val());

And try again.

Explanation: The NaN (Not-a-Number) is a weirdo Global Object in javascript frequently returned when some mathematical operation failed. This property indicates that a value is not a legal number..

Percetange calculation wrong result

The formula should be 1 minute / total minutes. So for 2 hrs, its 1 min / 120 min = 0.00833 which is 0.833%.

Javascript - Calculation Error

Floating point errors are quite normal, this is due to the problems inherent in representing some floating point numbers in binary.

Read this: What Every Computer Scientist Should Know About Floating-Point Arithmetic.

JavaScript Calculating wrong

You can use calculate for all changes instead of creating each one for each input, which makes the calculation complex.

// Get reference to inputs.var page = document.getElementById("page");var total = document.getElementById("total");var dup = document.getElementById("ckbox1");var laser = document.getElementById("ckbox2");
function calculate() { // To Number var pages = parseInt(page.value, 10); var value = 0;
if (pages <= 10) { value = 1; } else { var extra_pages = pages - 10; var new_total = extra_pages * .10; var new_total1 = 1 + new_total; value = new_total1; } // Add 10 if dup is checked. if (dup.checked) { value += 10; } // Add 15 if laser is checked. // These can be moved out like // const laserVal = 15; // value += laserVal if you don't want magic number here. if (laser.checked) { value += 15; } // Truncate float. total.value = value.toFixed(1);}
Enter a Number:<input type="text" id="page" value="1" oninput="calculate()"><br><br><br><br><br>duplicates:<input type="checkbox" id="ckbox1" onclick="calculate()">laser print:<input type="checkbox" id="ckbox2" onclick="calculate()"><br><br>Total:<input type="text" id="total">

JavaScript Integer math incorrect results

Per the ECMAScript standard, all numbers in JavaScript are (64-bit IEEE 754) floating-point numbers by default.

However all 32-bit integers can be exactly represented as floating-point numbers. You can force a result to 32 bits by using the appropriate bitwise operator, like this:

x = (a * b) >>> 0;  // force to unsigned int32
x = (a * b) | 0; // force to signed int32

Weird, but that's the standard.

(Incidentally this rounding behavior is one of the most frequently reported "bugs" against Firefox's JavaScript engine. Looks like it's been reported 3 times so far this year...)

If you want real integer math, you can use BigInt values, a different type of number, written with an n at the end:

> 119106029n * 1103515245n
131435318772912105n

This is a relatively recent JS feature, and may not be implemented in old browsers.


As for reproducible random numbers in JavaScript, the V8 benchmark uses this:

// To make the benchmark results predictable, we replace Math.random
// with a 100% deterministic alternative.
Math.random = (function() {
var seed = 49734321;
return function() {
// Robert Jenkins' 32 bit integer hash function.
seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff;
seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff;
seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff;
seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff;
seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff;
seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff;
return (seed & 0xfffffff) / 0x10000000;
};
})();

Javascript date calculation returns incorrect values

45 is 31 + 14. 31 days after December 1 is January 1, 14 days after January 1 is January 15.

The result is correct. Date arithmetic that crosses month boundaries is off by 1 because there's no day 0 in months.

The reason you're getting November 14 in the first case is because daylight savings time changes sometime in October. Your afterTime() function treats all days as 24 hours long, but when DST ends we add an extra hour to that day. So you're going from Oct 1 00:00:00 to Nov 14 23:00:00 instead of Nov 15 00:00:00.

Use the built-in date arithmetic in the Date class, it automatically adjusts for this.

resultDate.setTime(afterTime(startDate.getTime(), 45));


Related Topics



Leave a reply



Submit