Javascript increment operator - javascript

totalvalue = 0;
for (x=1; x<6; x++)
{
totalvalue += document.getElementById("rcv_amount_"+x).value;
}
rcv_amount_1 = 2
rcv_amount_2 = 4
rcv_amount_3 = 6
expected result is 12, but i am getting 0246.
Any help?

You have to convert the .value into a number - initially the .value property of an <input> element is a string, so the += operator results in concatenation, not addition.
To convert a string value into a number you can use parseInt(..., 10) for integers, or parseFloat(...) or just +(...) for non-integers.

Try with
totalvalue += parseInt(document.getElementById("rcv_amount_"+x).value, 10);

Related

Adding 1 to a css style property in Javascript

I am trying to first get the value of the order property of an element, and then adding 1 to it when I click a button. Thing is, instead of getting 1 and adding 1 and getting 2, I get 11. Shouldn't the "+=" operator add the values? What am I doing wrong?
carouselPrev.addEventListener("click", function(){
const firstPost = document.querySelector(".blog-post");
let firstPostOrder = firstPost.style.getPropertyValue('order');
firstPost.style.order = firstPostOrder += 1;
});
Css properties are strings, and '1' + 1 = 11.
Add "+" before firstPostOrder to convert it to a number.
firstPost.style.order = +firstPostOrder += 1;
the values are strings so they are be concatenated, try parsing to an integer before using parseInt()
Try this
carouselPrev.addEventListener("click", function(){
const firstPost = document.querySelector(".blog-post");
let firstPostOrder = firstPost.style.getPropertyValue('order');
firstPost.style.order = parseInt(firstPostOrder,10) +1;
});
No, the "+=" operator is an assignment operator you'd use in lieu of "=".
let x = 42;
x += 1;
is equivalent to
let x = 42;
x = x + 1;
You want to use just the "+" to add the values, not the "+=".

Incorrect result while adding with parseFloat in Javascript

I want to perform addition of floating point numbers. I will always have always have only 2 decimal places.
However if I do:
var num = 0;
num += parseFloat("2434545.64").toFixed(2);
num += parseFloat("454560.91").toFixed(2);
I get the value as 02434545.64454560.91
It is appending instead of adding. Also will the addition be accurate always?
toFixed() return a String.
So you concatenate two String.
You should use toFixed() only in the last statement and you should not mix this invocation with a += operator in a even statement because here :
num += parseFloat("2434545.64").toFixed(2);
parseFloat("2434545.64").toFixed(2) is evaluated first.
It produces a String.
Then its num += String result is evaluated.
So, it would concatenate a Float with a String. Which produces again a String concatenation and not an arithmetic operation.
Just invoke toFixed() in a distinct statement :
var num = 0;
num += parseFloat("2434545.64");
num += parseFloat("454560.91");
num = num.toFixed(2);
Here you go with the solution
var num = 0;
num += 2434545.64;
num += 454560.91;
console.log(parseFloat(num).toFixed(2));
Here is the documentation for parseFloat https://www.w3schools.com/jsref/jsref_parsefloat.asp

Sum all html fields money values

I have a function to sum values with same ID; jsFiddle. This works, but not if is a decimal value, like a money value. (10,05 + 1.005,10, example)
$('#button-cart').on('click', function() {
var MaxSelectionNum = "7";
var sum = 0;
// Loop through all inputs with names that start
// with "option-quantity" and sum their values
$('input[name^="option-quantity"]').each(function()
{
console.log(parseInt($(this).val()));
sum += parseInt($(this).val()) || 0;
});
if (sum < MaxSelectionNum)
{
$(".errorQuantity").html("Please select 7 meals").show();
}
else
{
$(".errorQuantity").html("You have select greater than 7: meal count: " + sum).show();
}
});
How can we fix it?
Use parseFloat instead of parseInt when dealing with decimal values.
parseInt() function parses a string argument and returns an integer or NaN. If not NaN, the returned value will be the integer representation of the string passed in.
parseFloat() function parses a string argument and returns a floating point number or Nan(If the string expression cannot be converted to a numerical value).
Here is a working sample.
You must use parseFloat:
just replace your current code with the following one:
$('#button-cart').on('click', function() {
var MaxSelectionNum = "7";
var sum = 0;
// Loop through all inputs with names that start
// with "option-quantity" and sum their values
$('input[name^="option-quantity"]').each(function()
{
console.log(parseFloat($(this).val()));
sum += parseFloat($(this).val()) || 0;
});
if (sum < MaxSelectionNum)
{
$(".errorQuantity").html("Please select 7 meals").show();
}
else
{
$(".errorQuantity").html("You have select greater than 7: meal count: " + sum).show();
}
});
This gonna help you :)
I've updated your script a bit (js lines 10-16)
https://jsfiddle.net/La18Lcns/10/
If you want to use number taplate such as
1.142,32
23.456,5
1.500
First you need to conver it to float format
1142.32
23456.5
1500
Than you use parseFloat() instead ParseInt()
$('#button-cart').on('click', function()
{
var MaxSelectionNum = "7";
var sum = 0;
// Loop through all inputs with names that start
// with "option-quantity" and sum their values
$('input[name^="option-quantity"]').each(function()
{
console.log(parseFloat($(this).val()));
sum += parseFloat($(this).val()) || 0;
});
if (sum < MaxSelectionNum)
{
$(".errorQuantity").html("Please select 7 meals").show();
}
else
{
$(".errorQuantity").html("You have select greater than 7: meal count: " + sum).show();
}
});

How do I stop parseFloat() from stripping zeroes to right of decimal

I have a function that I'm using to remove unwanted characters (defined as currency symbols) from strings then return the value as a number. When returning the value, I am making the following call:
return parseFloat(x);
The problem I have is that when x == "0.00" I expect to get 0.00 (a float with two decimals) back. What I get instead is simply 0.
I've also tried the following:
return parseFloat(x).toFixed(2);
and still get simply 0 back. Am I missing something? Any help would be greatly appreciated.
Thank you!!
parseFloat() turns a string into a floating point number. This is a binary value, not a decimal representation, so the concept of the number of zeros to the right of the decimal point doesn't even apply; it all depends on how it is formatted back into a string. Regarding toFixed, I'd suggest converting the floating point number to a Number:
new Number(parseFloat(x)).toFixed(2);
this should work:
return parseFloat(x).toFixed(2);
you can test it by running this in firebug:
var x = '0.00';
alert(parseFloat(x).toFixed(2));
simple:
function decimalPlaces(float, length) {
ret = "";
str = float.toString();
array = str.split(".");
if (array.length == 2) {
ret += array[0] + ".";
for (i = 0; i < length; i++) {
if (i >= array[1].length) ret += '0';
else ret += array[1][i];
}
} else if (array.length == 1) {
ret += array[0] + ".";
for (i = 0; i < length; i++) {
ret += '0'
}
}
return ret;
}
console.log(decimalPlaces(3.123, 6));
For future readers, I had this issue as I wanted to parse the onChange value of a textField into a float, so as the user typed I could update my model.
The problem was with the decimal place and values such as 12.120 would be parsed as 12.12 so the user could never enter a value like 12.1201.
The way I solved it was to check to see if the STRING value contained a decimal place and then split the string at that decimal and then count the number of characters after the place and then format the float with that specific number of places.
To illustrate:
const hasDecimal = event.target.value.includes(".");
const decimalValue = (hasDecimal ? event.target.value.split(".") : [event.target.value, ""])[1];
const parsed = parseFloat(event.target.value).toFixed(decimalValue.length);
const value = isNaN(parsed) ? "" : parsed;
onEditValue(value);
Here is dynamic version of floatParser for those who need
function customParseFloat(number){
if(isNaN(parseFloat(number)) === false){
let toFixedLength = 0;
let str = String(number);
// You may add/remove seperator according to your needs
[".", ","].forEach(seperator=>{
let arr = str.split(seperator);
if( arr.length === 2 ){
toFixedLength = arr[1].length;
}
})
return parseFloat(str).toFixed(toFixedLength);
}
return number; // Not a number, so you may throw exception or return number itself
}

Javascript: why does this produce and ugly string??? I would like currency

var total = 0;
$(".amount").each(function () {
var value = $(this).val();
value = (value.length < 1) ? 0 : value;
var tmp = parseFloat(value).toFixed(2);
total += tmp;
});
$(".total").text(total);
I am trying to loop through some text boxes and sum up their values. This produces a nasty string. What am I missing?? if I put 8 in the first textbox total text ends up as " 08.000.000.000.00". What am I doing wrong? I would like to format as currency but if not, at least just a two decimal number. Any pointers?
.toFixed converts the object from a Number to a String.
Leave the full values in place and only convert using .toFixed at the very end
$(".total").text(total.toFixed(2));
Alternatively, convert the string back to a number.
total = total + + tmp;
Just FYI, there is an excellent mathematical aggregation plugin for jQuery: jQuery Calculation
Using that plugin may also indirectly solve your issue.
It's usage would reduce your script to:
$('.total').text($('.amount').sum());
You are converting the parseFloat into a string, then adding it to total. Only add .toFixed(2) to the final line, once things have been added.
var total = 0;
$(".amount").each(function() {
var value = $(this).val();
value = (value.length < 1) ? 0 : value;
var tmp = parseFloat(value);
total += tmp;
});
$(".total").text(total).toFixed(2);

Categories