This calculation script works almost, but it doesn't do anything with a value with a number behind the comma. Can anyone help me?
var selects = $('select');
var inputs = $('input');
selects.change(calculate);
inputs.keyup(calculate);
function calculate()
{
var runningTotal = 0;
selects.each(function(i)
{
var val = parseInt($(this).val());
var qty = inputs.eq(i).val();
runningTotal += (val*qty);
});
$('#grandtotal').val(runningTotal);
}
If you're trying to convert a string to a number with a decimal point, don't use parseInt(), but parseFloat() instead.
jsfiddle: http://jsfiddle.net/Grimbode/mjs32/1/
alert(parseInt('10.10'));
alert(parseFloat('10,10'));
alert(parseFloat('10.10'));
You need to convert you commas to '.'s apparantely for the parseFloat() to work.
parseFloat(('10,10').replace(",", "."));
selects.each(function(i)
{
var val = parseInt($(this).val());
if (val.indexOf('"') != -1) {
val = val.replace(/"/g, '');
}
var qty = inputs.eq(i).val();
runningTotal += (val*qty);
});
Related
I have an input field where users can enter decimal numbers by using a Dot or a comma ( Example: 79,99 or 79.99 ) . When users enter the number with a comma I replace it with a dot ( this number is then sent to a remote server for verification) . Now I would like to display the number after the user enters it in the footer using toFixed(2) function to display only the first two decimal numbers. I cant get it to work , because after converting it back to a number using ParseFloat the 2 decimals after the comma disappear.
Example:
User enter in the input field : 79,99 which is then set into the variable totalAmount:
$('#amount-1').keyup(function() {
getRefundAmount(1); // This function calls the calcTotalAmount function
})
function calcTotalAmount() {
console.log('calcTotalAmount');
var totalAmount = 0;
var totalRefund = 0;
var rowAmount = 0;
var rowRefund = 0;
for(var i = 1; i < 4; i++ ) {
rowAmount = parseFloat($('#amount-' + i).val());
rowRefund = parseFloat($('#result-' + i).text());
if(!isNaN(rowAmount)) {
totalAmount += rowAmount;
totalRefund += rowRefund;
}
}
var toPay = totalAmount-totalRefund;
totalAmount = totalAmount.toString().replace(/\,/g, '.');
totalAmount = parseFloat(totalAmount).toFixed(2);
$('#footer-refund').text(totalRefund)
$('#footer-total').text(totalAmount)
if (totalAmount == '') {
$('#footer-total').text("0.00");
}
}
The Result displayed in the footer is : 79.00 instead of 79.99
I tried your code in jsfiddle and got an error on the ".toFixed(2)"
After changing it a bit i could prevent the error.:
$(function() {
var totalAmount = '79,99';
totalAmount = parseFloat( totalAmount.toString().replace(/\,/g, '.'));
totalAmount = totalAmount.toFixed(2);
$('#footer-refund').text(totalAmount)
});
https://jsfiddle.net/jkrielaars/2gb59xss/1/
It seems like the code you've given works just fine but there are some fixes you could apply :
totalAmount = ("" + totalAmount).replace(/\,/g,'.');
totalAmount = parseFloat(totalAmount);
//use toFixed only if you don't restrict input to 2 decimals, but I'd recommend restricting input otherwise you'll encounter rounding issues
Btw, you do $('#footer-refund').text(totalRefund.toFixed(2)), shouldn't it be $("#footer-refund").text(totalAmount) (not sure why you use toFixed here too) ?
Thanks for all the help :
solution is as follows : I have to check it in the for loop already and replace it there.
for(var i = 1; i < 4; i++ ) {
if(!$('#amount-' + i).val()){continue;}else{
rowAmount = parseFloat($('#amount-' + i).val().toString().replace(/\,/g,'.'));
rowRefund = parseFloat($('#result-' + i).text());
if(!isNaN(rowAmount)) {
totalAmount += rowAmount;
totalRefund += rowRefund;
}
}
}
I have a table of fines people owe:
<tr><td class='fines'>104.20</td></tr>
<tr><td class='fines'>26.40</td></tr>
<tr><td class='fines'>99.14</td></tr>
I am trying to get the sum of the cells:
var sumFines = "";
$.each($('.fines'),function(){
alert($(this).html());
sumFines += parseFloat($(this).html());
})
alert(sumFines);
The result of each alert in each loop is the number in the cell. The result of the final alert is "NaN", Why?
When you sum
"" + 120
the result return a string, you must sum number, so change
var sumFines = "";
to
var sumFines = 0;
I need to set initial value of sumFines to 0.
var sumFines = 0;
$.each($('.fines'),function(){
alert($(this).html());
sumFines += parseFloat($(this).html());
})
alert(sumFines);
var sumFines = ""; makes sumFines a string and that's the reason you get NaN because you are doin arithmatic operations with a string and float which can't be cast together.
If you want to keep the .each approach, just change your initial value to 0.
var subtotal = 0;
$('.fines').each(function() {
subtotal += !isNaN(+$(this).html()) && +$(this).html();
});
alert(subtotal);
The line:
!isNaN(+$(this).html()) && +$(this).html();
asserts that you are effectively adding a number, else nothing.
fiddle
http://jsfiddle.net/hem7q4fn/2/
Nan reduce whole expression to NaN
try:
var sumFines = 0;
$('.fines').each(function () {
var num = parseFloat($(this).txt());
sumFines += isNaN(num) ? 0 : num;
});
alert(sumFines);
Currently I am using following jQuery code to filter only digits:
$('#input_field').keyup(function(e) {
if (/\D/g.test(this.value)) {
this.value = this.value.replace(/\D/g, '');
}
});
But I want to get floating point numbers(upto to 2 decimal places) like this:
10.2
1.23
1000.10
Try this regex:
/^\d+(\.\d{0,2})?$/
Your JS:
$('#input_field').keyup(function(e) {
var regex = /^\d+(\.\d{0,2})?$/g;
if (!regex.test(this.value)) {
this.value = '';
}
});
try
toFixed(2)
eg:
var number = 2.234239;
var numberfixed=number.toFixed(2);
I think you have to use typing interval, because keyup is to quick and the regex don't approve something like this 0.
var typingTimer;
var doneTypingInterval = 1000;
$('.myInputField').keyup(function(){
clearTimeout(typingTimer);
if ($('.myInputField').val) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
function doneTyping () {
var vale = $('.myInputField').val();
var regexTest = /^\d+(?:\.\d\d?)?$/;
var ok = regexTest.test(vale);
if(!ok){
$('.myInputField').val('');
}
}
http://jsfiddle.net/jWbsE/
You need to change the regular expression used to test the values against.
/^\D+(\.\D\D?)?$/
This will allow numbers with no decimal point, or with a decimal point and one or two digits after.
var dot = fVal.split(".");
var len0 = 0;
var len1 = 0;
if (dot.length == 2) {
len0 = dot[0].length;
len1 = dot[1].length;
} else if (dot.length > 2)
len1 = 3;
else
len1 = 0;
var fValFlt = parseFloat(fVal);
var fValN = isNaN(fVal);
if ((len1 > 2) || fValN == true || fValFlt < 0) {
//failure arguments
} else {
//success arguments
}
In above code fVal is the field value for which you might be checking for.
I have a variable count set to zero.
var count = 0;
Then I run through a .each() loop to update the count. The .text() parameter will always return a text number.
$(this).find('.outersubtopic').each(function(idx)
{
var temp = $(this).text();
count += temp;
});
alert(count);
When I hit the alert, it always reads 0008 instead of just 8.
How do I turn the .text() into a real number?
$(this).find('.outersubtopic').each(function(idx)
{
var temp = $(this).text();
count += window.parseInt(temp);
});
alert(count);
window.parseInt() should do it for you.
you have to convert it to an Number
$(this).find('.outersubtopic').each(function(idx)
{
var temp = $(this).text();
count += Number(temp);
});
alert(count);
try using parseInt
$(this).find('.outersubtopic').each(function(idx)
{
var temp = $(this).text();
count += temp;
});
alert(parseInt(count));
count += 1 * temp; // quick way to change string to number
I need to sum some money value, i have this html
<div class=''>54,44</div>
<div class=''>34,10</div>
<div class=''>44,00</div>
<div class=''>14,50</div>
How can i make an alert with the sum of these div text?? ( the right sum!! ;-) )
Many thanks!
Add some class like money (or use $("div") selector) and do something like this:
var sum = 0;
$(".money").each(function(){
sum += parseFloat($(this).text().replace(",", "."));
});
alert(sum);
Firstly, its worthwhile putting a data-attribute on each div with the raw amount, devoid of any locale-specific formatting.
eg/
<div data-amount="55.44">54,44</div>
Then assuming these div's are identifiable you can simply do
var total = 0;
$('some-selector-for-your-divs').each(function(){
total += parseFloat($(this).data('amount'));
});
Edit: Duh! parseInt on monetery amounts fixed.
A comma isn't a legal decimal separator in Javascript, so you'll have to convert the commas into decimal points:
var sum = 0;
$('div').each(function() {
var v = $(this).text().replace(',', '.');
sum += parseFloat(v);
});
alert(sum);
var sum = 0;
$('div').each(function() {
sum += $(this).text();
});
alert("The sum is "+ sum);
Use following code
var sum=0;
$('div').each(function(){
sum+=parseFloat($(this).text().replace(',','.');
});
var sum = 0;
$('div').each(function() {
var val = $(this).text().replace(',', '.'); // Replace , with .
sum += parseFloat(val);
});
(demo)
Update
The base 10 thing was crap.
var sum=0;
$('div').each(
function(){
sum+=Number($(this).html());
}
);
alert(sum );
Don't forget convert numbers to coreect format