jQuery - Strange rounding error with table calculations with some numbers - javascript

I've got a simple table that allows users to enter 2 numbers, and then a script then calculates the annual average and gets the totals for all rows that have the same option in the select menu.
I've setup a sample JSFiddle:
http://jsfiddle.net/fmdataweb/73Jzc/1/
that shows how this works. I've just noticed that at times I get a strange rounding error (I want it to round to one decimal place). For example if you select "moderate" and then enter 5 and 4 for an average of 0.4, then click the button to create a new row and select "moderate" again then enter 3 and 40 for an average of 2.3 you'll notice the total for the moderate is "2.6999999999999997" when it should be 2.7.
If you enter other numbers it's fine so far in my testing but for some reason these combinations don't get rounded for the totals and I'm not sure why. Appreciate if anyone can point out the error in my script. Here's the script that does the averages and totals:
$('#nextYear')
.on('change', 'select', calc)
.on('keyup', 'input', calc);
function calc(){
$('#nextYear tr:has(.risk)').each(function(i,v){
var $cel = $(v.cells);
var $risk = $cel.eq(1).find('option:selected').val();
var $numb = $cel.eq(2).find('input').val();
var $weeks = $cel.eq(3).find('input').val();
var $avg = ($numb * $weeks) / 52;
var $avgRounded = Math.round( $avg * 10 ) / 10;
$cel.eq(4).find('input').val($avgRounded);
});
var tot = {};
$('#nextYear tr:has(.risk) option:selected')
.map(function(i){
var el = $(this).val();
var qty = parseFloat($('#nextYear tr:has(.risk)').eq(i).find('td:last').prev().find('input').val());
if (!tot.hasOwnProperty(el)) {
tot[el] = 0;
}
tot[el] += qty
return tot;
}).get();
// console.log(tot);
$('#textfield6').val(tot.moderate);
$('#textfield7').val( tot.high );
}
​

You problem is here:
$('#textfield6').val(tot.moderate);
$('#textfield7').val( tot.high );
You must round them like you did with
var $avgRounded = Math.round( $avg * 10 ) / 10;
or using .toFixed(1)
Edit:
Then, the code is:
$('#textfield6').val(tot.moderate.toFixed(1));
$('#textfield7').val(tot.high.toFixed(1));
You can see it here: http://jsfiddle.net/73Jzc/2/

Try $avg.toFixed(1); instead of Math.round( $avg * 10 ) / 10;

Related

Trying to make a simple JQuery/JavaScript calculation

I'm pretty fresh regarding JS/JQuery, and I'm trying to make a simple calculation/function based on a code I found earlier here. The original code works great, it sums a given col and appends the result as in a new row.
I'm now trying to get a percentage of said result.
<script>
var result = [];
$('#table tr').each(function(){
$('td#pay', this).each(function(index, val){
if(!result[index]) result[index] = 0;
result[index] += parseInt($(val).text());
});
});
var varTax = 24;
$('#table').append('<tr></tr>');
$(result).each(function(){
$('#table tr').last().append('<td colspan="3"> </td><td><b>Totalt</b></td><td id="sumOfPay">'+this+' kr</td><td colspan="2">'+( 100 - varTax ) / 100 * this+'</td>')
});
</script>
var taxCalc and var taxTot is what I've added. But this only prints [object Object].
Edit: I figured it out. The formula I was looking for was +( 100 - varTax ) / 100 * this+
The formula I was looking for was +( 100 - varTax ) / 100 * this+

DOM for GetElementsByName for-loop

I have a small "problem". I try to do a Loop-for for a
"getElementsByName" for each rows in the table.
I try to loop a few values.
Price * Quantity * discount * tax (select.options) = MY Final price after discout.
AD: (You have to open Full View)
For a single line it works great by getElementById. However, the need for the creation of the next line (Button Add Position). So i chose GetElementsByName
Also counted for him the value (in place "after rebate")
--EDIT--
I made a loop "For".
In html code I have a lot the same fields "named" (ex. cena, ile, rabat etc.)
So if I will had 3 rows with this fields I want to calculate for each line separately. But my loop doesn't work.
Full View you can see here:
http://codepen.io/warhero/pen/WwvLZE (121 line JS)
My JS code:
var i;
for (i = 0; i < document.getElementsByName('kwotarabat').length; i++) {
var cena = parseInt(document.getElementsByName('cena')[i].value);
var ile = parseInt(document.getElementsByName('ile')[i].value);
var rabat = parseInt(document.getElementsByName('rabat')[i].value);
var vat = document.getElementsByName('vat')[i].options[document.getElementsByName('vat')[i].selectedIndex].value;
// vat value
var wynik = (ile * cena * vat);
// the net value
var wynik2 = cena * ile;
// net amount after discount
var wynikRabat = (wynik2 * (rabat / 100));
// gross amount after discount
var wynikRabatVat = (wynik * (rabat / 100));
// net amount after discount (display for customers)
var wynikNetto = (wynik2 - wynikRabat);
document.getElementsByName('kwotarabat')[i].innerHTML = (wynik + wynik2 - wynikRabat - wynikRabatVat).toFixed(2);
}
In Here >> http://codepen.io/warhero/pen/ONVEmZ is the code for a single row and calculations are correct.
Any Ideas ?

Javascript - X is what percent of X function/equation

My script dynamically produces a number and this can range from anything between 1-278.
I then need to do a number is what percent of 603.
Say for example that number turns out to be 67, i then need to know what percent 67 is of 603.
The function should return 11.1..%
Basically the second option on this page:
http://www.percentagecalculator.net/
Can i do this with javascript?
var total = 603;
var num = 67 // what have been created dynamically beforehand
num is what percent of total?
Well, you just do :
percentage = (num/total)*100;
Here you go:
var total = 603;
var num = 67 /*whatever was generated before*/;
var percentage = num / total * 100;
here is a jsfiddle to demonstrate my solution: http://jsfiddle.net/zfhkB/2/
Hope I helped :)

Javascript calculation not giving desired output

I have the following code:
function calculateVat() {
var vat = null;var amount=null;
vat = document.getElementById("hiddenvat").value;
amount = document.getElementById("numtxt_itemCost").value;
var total = parseInt(amount)* parseInt(vat) / 100 ;
document.getElementById("txt_Total_text").value = total;
}
Here I am calculating VAT price according to amount price
E.G. VAT value is 13.5
If I input 1780 on numtxt_itemCost Field then it should give the output 240.30,
but when I run this programme by putting value 1780 on numtxt_itemCost field
it shows the 231.4 which is the wrong output,
You should use parseFloat instead:
parseFloat(1780)* parseFloat(13.5) / 100 //240.3
when you use parseInt, all decimals get stripped off.
Try this:
function calculateVat() {
var vat = null;var amount=null;
vat = document.getElementById("hiddenvat").value;
amount = document.getElementById("numtxt_itemCost").value;
var total = parseInt(amount)* parseFloat(vat) / 100 ;
document.getElementById("txt_Total_text").value = total;
}
The problem is that you were converting the vat to an "int" using parseInt(vat), so the answer you were seeing was the result of a 13% vat rather than 13.5%.

Incrementing a number smoothly with a variable time period in JS

I have a really simple JS counter which I display on a dashboard like screen which does the following:
Every 5 minutes it makes an jsonp call and retrieves a "total" number
It then displays this number to the screen by incrementing the last total displayed till it is equal to the new total. (the number can only ever increase)
I'm having some trouble with making the number increment smoothly. What I would like to do is find a delta (i.e. New total - old total) and increment the number gradually over the 5 minutes till the next call so it looks like a nice smooth transition.
Any ideas on how I can do this?
Currently some of my code looks like this (This block get's called every 5mins. And yes, it's in dire need of a refactor...)
var LAST_NUMBER_OF_SESSIONS = null;
var five_minutes_in_seconds = 300;
var new_number_of_sessions;
$.getJSON('http://blah.com/live_stats/default_jsonp.aspx?callback=?', function(data) {
if(LAST_NUMBER_OF_SESSIONS === null){
LAST_NUMBER_OF_SESSIONS = data.total_sessions;
}
new_number_of_sessions = data.total_sessions;
var delta = Math.floor(new_number_of_sessions - LAST_NUMBER_OF_SESSIONS);
var time_interval = (five_minutes_in_seconds / delta) * 1000;
var old_value = LAST_NUMBER_OF_SESSIONS;
var new_value = null;
sessions_interval = setInterval(function (){
new_value = parseInt(old_value, 10) + 1;
$('#stats').text(new_value);
old_value = new_value;
if(new_value >= new_number_of_sessions){
clearInterval(sessions_interval);
}
}, time_interval);
LAST_NUMBER_OF_SESSIONS = new_value;
});
}
This code it seems to increment the number very quickly at the start of the 5min period and then stop so it's not exactly right...
Try this:
var total = 0,
delta = 0,
stats = $('#stats').text( total );
function increment() {
var v = +stats.text();
if ( v < total ) {
stats.text( v + 1 );
} else {
$.getJSON('http://...', function(data) { // added data here
delta = Math.floor( 300000 / ( data.total_sessions - total ) );
total = data.total_sessions;
});
}
setTimeout(increment, delta);
}
Update:
In order to test my code, I had to simulate the JSON reponse - I used an array of numbers. See here: http://jsfiddle.net/simevidas/MwQKM/
(In the demo, I use an interval of 5 seconds instead of 5 minutes.)
I am not exactly sure why your code doesn't work as expected, although I suspect that it has to do with line LAST_NUMBER_OF_SESSIONS = new_value;. I wrote something similar and it works fine. It's not that different from what you have, minus that last line of code.

Categories

Resources