Calculate parseint with decimal - javascript

I found this in another post:
<script language='javascript'>
function AddInputs()
{
var total = 0;
var coll = document.getElementsByClassName('add')
for ( var i = 0; i<coll.length; i++)
{
var ele = coll[i];
total += parseInt(ele.value);
}
var Display = document.getElementById('Display');
Display.innerHTML = total;
}
</script>
It works, but 1.50, 1.50, and 1.50 = 3 which isn't accurate. I'm new to JS (only know PHP), but I looked into it and figure it has something to do with parseInt since 1.50 isn't a whole number. Is there something I can replace parseInt with to calculate it so that the three 1.50 actually equals 4.50?

Try to use parseFloat() instead of parseInt()
Also use <script type="text/javascript"> instead of <script language="javascript"> that will be more standard and correct

parseInt will convert any decimal to an integer so parseInt(1.5) becomes 1. That is why parseInt(1.5) + parseInt(1.5) + parseInt(1.5) = 3. If you want it to equal 4.5 then just replace parseInt with parseFloat:
function AddInputs()
{
var total = 0;
var coll = document.getElementsByClassName('add')
for ( var i = 0; i<coll.length; i++)
{
var ele = coll[i];
total += parseFloat(ele.value);
}
var Display = document.getElementById('Display');
Display.innerHTML = total;
}

When you call parseInt on 1.50 you're getting the integer part of that value (1 in this case). Just replace parseInt with parseFloat and you'll get the value you expect.

Beside parseFloat you can also use Number to convert a string to a numeric value.
document.querySelector('#add').addEventListener('click', addNumber)
var total = 0;
function addNumber(e) {
total += Number(document.querySelector('#plus').value);
document.querySelector('#result').innerHTML = 'total: '+total.toFixed(2);
}
<input id="plus" type="number" placeholder="type a number"/>
<button id="add">add to total</button>
<div id="result"></div>

Related

Calculate the sum of multiple currency formatted elements

I am trying to create a sub-total based on a series of currency formatted numbers but am struggling converting the numbers back to integers so that they can be added. Here's what I have tried:
$(function() {
var totals = $('.price');
var sum = 0;
for (var i = 0; i < totals.length; i++) {
//strip out dollar signs and commas
$(totals[i].text()).replace(/[^\d.]/g, '');
//convert string to integer
var ct = parseFloat($(totals[i].text()));
sum += ct;
}
console.log(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$195,000.20</div>
<div class="price">$21,404.00</div>
<div class="price">$7,000.00</div>
<div class="price">$450.00</div>
replace() doesn't modify the string passed in (and it couldn't here anyway, since it's the result of a function). It just returns the modified value.
Save the result of replace(), and sum based on that:
$(function() {
var totals = $('.price');
var sum = 0;
for (var i = 0; i < totals.length; i++) {
//strip out dollar signs and commas
var v = $(totals[i]).text().replace(/[^\d.]/g, '');
//convert string to integer
var ct = parseFloat(v);
sum += ct;
}
console.log(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$195,000.20</div>
<div class="price">$21,404.00</div>
<div class="price">$7,000.00</div>
<div class="price">$450.00</div>
Also: note the typo -- you want $(totals[i]).text(), not $(totals[i].text())

How can I add up two or more array elements (numbers)

I want to add up all of the element from var string to each other.
I did try this but now I want to do this for each element.
var operator = document.getElementById("operation").value;
var number = document.getElementById("numbers").value;
var string = number.split(",");
var number1 = string[0];
var number2 = string[1];
var sum = number1 + number2;
document.getElementById("result").innerHTML = parseInt(sum);
Any help is welcome!
Use reduce() and don't forget to cast your string into int:
var number = "1,2,3,4,5"
var sum = number.split(",").reduce(function (total, num) {
return total + parseInt(num);
}, 0);
You can do R. Saban's way and there are also other ways as well. For example try this:
var start = 0; // Using this to add each element in the array starting from 0, look below
var number = document.getElementById("numbers").value;
var string = number.split(",");
string.forEach(function (num) {
start += parseInt(num);
});
// variable "start" will hold the end result

I want the sum not the string, how?

This gives me the string: "01234" instead of 1+2+3+4=10, why?
I'd like to get the sum of the numbers not of the string.
Thanks.
<script type="text/javascript">
var i=1;
var totale=0;
var index = Array();
var domanda = 0;
while (domanda !== "end") {
domanda = prompt("Write a number, the total so far is: "+totale);
index[i]=domanda;
totale += index[i];
i++;
}
document.writeln("total: " + totale);
document.writeln("ended");
</script>
Because prompt() (which you should not be using) returns a string.
Wrapping the return in a parseInt(domanda) would fix it.
You need to parseInt the value coming back from the prompt, otherwise you're concatenating strings.
index[i]= parseInt(domanda);
You'll probably want to check whether the input value is a number too.
Use JavaScript's built in parseInt, this creates an int of anything passed into it, so: parseInt(value);
Just like this:
index[i]=Number(domanda);
Full script
<script type="text/javascript">
var i=1;
var totale=0;
var index = Array();
var domanda = 0;
do {
domanda = prompt("Write a number, the total so far is: "+totale);
if (domanda !== "end" && !isNaN(Number(domanda)))
{
index[i]=Number(domanda);
totale += index[i];
i++;
}
} while (domanda !== "end")
document.writeln("total: " + totale);
document.writeln("ended");
</script>

Add all values with input name="TotalInline[]"

How to add values from all input with name name="TotalInline[]"?
The following does not seams to work:
var total = 0;
$.each('input[name="TotalInline[]"];,function() {
total += this;
});
This should work :
var total = 0;
$('input[name="TotalInline"]').each(function() {
// assuming you have ints in your inputs, use parseFloat if those are floats
total += parseInt(this.value, 10);
});
var total = 0;
$.each($('input[name="TotalInline[]"]'), function() {
total += parseInt(this.value, 10);
});
You have some serious syntax errors, try this:
var total = 0;
$('input[name="TotalInline[]"]').each(function () {
total += parseInt(this.value, 10);
});
Try like this...
var total = 0;
$('input[name="TotalInline[]"]').each(function() {
total += parseInt($(this).val(),10);
});
var total = 0;
$('input[name="TotalInline[]"]').each(function() {
total += +this.value.replace(/[^\d.]/g, '');
});
Uses a quick regex to filter out only the numbers (and decimal point).
Uses a + prefix to convert to a number.

Decimal places in JS

I have two form inputs which display the calculated invoice sub-total and total of a form.
The problem I'm having is it's not displaying 2 decimal places.
Subtotal function:
function calcProdSubTotal() {
var prodSubTotal = 0;
$(".row-total-input").each(function(){
var valString = $(this).val() || 0;
prodSubTotal += parseInt(valString);
});
$("#product-subtotal").val(prodSubTotal);
};
Total function
function calcOrderTotal() {
var orderTotal = 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var productTax = $("#product-tax").val() || 0;
var orderTotal = parseInt(productSubtotal) + parseInt(productTax);
var orderTotalNice = "$" + orderTotal;
$("#order-total").val(orderTotalNice);
};
How do I go about displaying two decimal places?
change $("#product-subtotal").val(prodSubTotal);
to $("#product-subtotal").val(addDecimals(prodSubTotal));
and change $("#product-subtotal").val(prodSubTotal);
to $("#product-subtotal").val(addDecimals(prodSubTotal));
function addDecimals(a){
a += "";
var i=a.indexOf('.');
if(i<0){
return a + ".00";
}
var j = a.substring(i);
console.log(j);
if(j.length<3){
for(var k=j.length;k<3;k++)
a+='0';
return a;
}
if(j.length>3){
return a.substring(0, i)+j.substring(0,3);
}
}
You may want to look here:
http://www.mredkj.com/javascript/nfbasic2.html
Basically you can use toFixed(2), but then you get some rounding.
Or, if rounding is bad you can do parseInt(productTax * 100) / 100.
If you are working with real numbers it would be better to use parseFloat instead of parseInt. To format the number you could use the toFixed function:
$("#product-subtotal").val(prodSubTotal.toFixed(2));

Categories

Resources