I have an issue in doing a simple addition and save the value in a variable.
Basically I have the following code:
var accsen;
var lowsev = parseInt(accsen);
var hisev = parseInt(accsen) + parseInt(0.65);
console.log('Lowsev: ' + lowsev);
console.log('Hisev: ' + hisev + ' Type: ' + typeof(hisev));
console.log('Accsen: ' + accsen);
The variable accsen is being given a value from the database. Lowsev is being assigned the same value as accsen,while hisev is being assigned the value of accsen + 0.65.
However the issue I am having is that both lowsev and hisev are remaining 0. On doing console.log I get these values:
Lowsev: 0
Hisev: 0 Type: undefined
Accsen: 0.75
Can anyone tell me what I am doing wrong in the addition? Am I using the correct operators?
Sounds like you want to use parseFloat instead of parseInt.
"Lowsev is being assigned the same value as accsen" It's not, you're rounding it to an integer.
But parseInt() doesn't round properly. 0.75 comes out as 0, so it's working. Assuming you actually want to round these values try
var accsen;
var lowsev = Math.round(accsen);
var hisev = Math.round(accsen) + Math.round(0.65);
EDIT given the response
Your JS is treating accsen as a string, you need to convert to a number
var accsen = '0.75'; // as other people have noted this val in your code is missing.
var lowsev = parseFloat(accsen);
var hisev = parseFloat(accsen) + 0.65;
Related
Just a simple question. Having the next piece of code:
function addMarker(data) {
var types = {'meet': 380 + ',' + 95, 'vegetable': 285 + ',' + 0};
var selection = data.type;
console.log(types["meet"]);
console.log(types[selection]);
console.log(selection);
and having these results in the console:
380,95
undefined
Meet
I'd need to have in the second case also a 380,95. selection is supposed to be a string coming from the data object. Somehow when using this string like a dictionary key it's not working. How could I do then to get different values from types in some dynamic way like this?
Just to clarify, I'm not trying to get float numbers, what I need are two numbers separated by a ,
Javascript is case sensitive. Object has property meet whereas value of Selection is Meet. Hence, you will need to update your code to following
console.log(types[selection.toLowerCase()]);
For reference, String.toLowerCase()
Please check if
data.type === "Meet" // true
It should be "meet".
Btw. it is spelled meat, not meet.
Just to be clear
addMarker({'type':'meet'}) // would produce correct result
addMarker({'type':'Meet'}) // would produce result result you see
To correct this you could use lower Case String ,as provided by Nikhil
function addMarker(data) {
var types = {'meet': 380 + ',' + 95, 'vegetable': 285 + ',' + 0};
var selection = data.type;
selection = selection.toLowerCase();
console.log(types["meet"]);
console.log(types[selection]);
console.log(selection);
}
Or simply make proper call
This question already has answers here:
Javascript to convert string to number? [duplicate]
(4 answers)
Closed 7 years ago.
I am pretty new in JavaScript and JQuery and I am having a strange behavior with a simple mathematical sum into a JQuery function that retrieve numbers from some input field inside a JSP page (I can't put a JSFiddle because the values are take from jsp model object)
So, this is my JQuery function:
$("#variazioneUlterioreSaldoInput").bind('change keyup', function() {
console.log("VALUE CHANGED !!!");
var ulterioreSaldo = $("#variazioneUlterioreSaldoInput").val(); // Non ha separatori di migliaia o di decimanli quindi non devo eseguire replace
var saldo = $("#saldo").val().replace(/[^0-9,]/g, '').replace(",",".");
var anticipo = $("#anticipo").val().replace(/[^0-9,]/g, '').replace(",",".");
var totalePagamento = ulterioreSaldo + saldo + anticipo;
console.log("ulterioreSaldo: " + ulterioreSaldo );
console.log("ulterioreSaldo type: " + typeof ulterioreSaldo);
console.log("saldo: " + saldo);
console.log("saldo type: " + typeof saldo);
console.log("anticipo: " + anticipo);
console.log("anticipo type: " + typeof anticipo);
console.log("totalePagamento: " + totalePagamento);
console.log("totalePagamento type: " + typeof totalePagamento);
});
that retrieve and sum 3 values obtained from 3 differents input fields.
So for the values retrieved from the input tags having id="saldo" and id="anticipo" I apply a replace with 2 regex because these are strings that represent formatted number so before sum I have to obtain a plain number.
The problem is that when I perform the sum of these values by this line:
var totalePagamento = ulterioreSaldo + saldo + anticipo;
I obtain this wrong outout related to the sum: totalePagamento: 0.010.004499.48, this is the entire log into the FireBug Console.
VALUE CHANGED !!!
ulterioreSaldo: 0.01
ulterioreSaldo type: string
saldo: 0.00
saldo type: string
anticipo: 4499.48
anticipo type: string
totalePagamento: 0.010.004499.48
totalePagamento type: string
As you can see I have also printed the type of the retrieved objects and seems that are String and not Number so when I use the + operator these values are concatenated and not summed.
How can I correctly converts these values into Number and sum it?
Since you are adding decimal numbers try using parseFloat method:
var totalePagamento = parseFloat(ulterioreSaldo) + parseFloat(saldo) + parseFloat(anticipo);
And if you want only 2 digits after decimal use:
totalePagamento.toFixed(2);
use parseFloat() to sum the values
var totalePagamento = parseFloat(ulterioreSaldo) + parseFloat(saldo) + parseFloat(anticipo);
totalePagamento = totalePagamento.toFixed(2); //it will set floating point to 2 values e.g. 40.22
You have to use parseFloat() function to convert string into numbers. The parseFloat() function parses a string argument and returns a floating point number.
$(document).ready(function(){
var ulterioreSaldo = "0.01";
var saldo = "0.0";
var anticipo = "4499.48";
var sum = parseFloat(ulterioreSaldo) + parseFloat(saldo) + parseFloat(anticipo);
alert(sum);
});
Here is a Demo for the same.
I was making a survey in Qualtrics, and needed to have my items show different values of the slider depending on a variable, in my case, the value from a loop and merge. That didn't seem like a thing that you could do with piped text, so I had to figure out how to do it in Javascript.
I'm just posting this as an opportunity to provide the answer I found on my own. As usual with Qualtrics, your mileage may vary, and this may need to be modified for your specific situation. In particular, the question IDs and postTags change depending on whether it is in a loop/merge, and perhaps on other factors.
Put the following code into the javascript section of the question:
// Set the slider range
// First define the function to do it
setSliderRange = function (theQuestionInfo, maxValue) {
var postTag = theQuestionInfo.postTag
var QID=theQuestionInfo.QuestionID
// QID should be like "QID421"
// but postTag might be something like "5_QID421" sometimes
// or, it might not exist, so play around a bit.
var sliderName='CS_' + postTag
window[sliderName].maxValue=maxValue
// now do the ticks. first get the number of ticks by counting the table that contains them
var numTicks = document.getElementsByClassName('LabelDescriptionsContainer')[0].colSpan
// do the ticks one at a time
for (var i=1; i<=numTicks; i++) {
var tickHeader='header~' + QID + '~G' + i
// the first item of the table contains the minimum value, and also the first tick.
// so we do some tricks to separate them out in that case.
var tickSpanArray = $(tickHeader).down("span.TickContainer").children
var tickSpanArrayLength=tickSpanArray.length
var lastTickIndex=tickSpanArrayLength - 1
var currentTickValue = tickSpanArray[lastTickIndex].innerHTML
currentTickValue=currentTickValue.replace(/^\s+|\s+$/g,'')
console.log('Tick value ' + i + ' is ' + currentTickValue)
// now get the new value for the tick
console.log('maxValue: ' + maxValue + ' numTicks: ' + numTicks + ' i: ' + i)
var newTickValue = maxValue * i / numTicks //the total number of ticks
tickSpanArray[lastTickIndex].innerHTML=newTickValue.toString()
console.log('Changed tick value to ' + newTickValue)
}
}
var currentQuestionInfo = this.getQuestionInfo()
var currentQuestionID = currentQuestionInfo.QuestionID
// Now call the function
setSliderRange(currentQuestionInfo, theMaxValueYouWant)
If you find my answers helpful, help raise my reputation enough to add "qualtrics" as a valid tag!! Or, if someone else with reputation over 1500 is willing to do it that would be very helpful!
the problem is
when I say:
alert(parseInt(document.frmFuture.txtDays.value) + 7);
(value is number that user input) it shows fine.
but when I say:
var tmp = document.frmFuture.txtDays.value;
alert(tmp + 7);
it gives me undefined.
Actually, I want to do some cals later using the input number. But it looks like impossible? how can i do that?
You forgot the parseInt.
var tmp = parseInt(document.frmFuture.txtDays.value);
alert(tmp + 7);
Now it should work.
I am working in JavaScript coding. I have created a text area with name OQ_0 and value "0". When i use eval() method for that field in JavaScript it is giving the value undefined. The below are the part of JavaScript code
var tempOpenQtyStr = "document.InitiateReturnsForm.OQ" + "_" + 0;
var tempOpenxQtyStr = eval(tempOpenQtyStr).value;
alert('Manuals =' + document.InitiateReturnsForm.OQ_0.value);
alert('eval(tempOpenxQtyStr ) =' + eval(tempOpenxQtyStr));
alert('eval(tempOpenxQtyStr).value =' + eval(tempOpenxQtyStr).value);
Output:
Manuals = 0
eval(tempOpenxQtyStr ) = 0 --- Here it is suppose to show "[object]"
eval(tempOpenxQtyStr).value = undefined.
Kindly help me out what is change to do. Thanks in advance.
Why not just use document.InitiateReturnsForm["OQ_" + 0].value?
Try
alert('eval(tempOpenxQtyStr ) = ' + eval(tempOpenQtyStr));
alert('eval(tempOpenxQtyStr).value = ' + eval(tempOpenQtyStr).value);
In the second and third alert you are evaluating the second variable which stores the value of the first evaluated object. That's why the error occurs.
alert('eval(tempOpenxQtyStr ) =' + eval(tempOpenxQtyStr));
Since you put a string, not an object, inside tempOpenxQtyStr, it evaluates that string and returns 0.
alert('eval(tempOpenxQtyStr).value =' + eval(tempOpenxQtyStr).value);
Here you're using a method on a variable that contains a string. That doesn't work. It doesn't have that method, that's why it returns undefinied.
You might want to try doing eval(tempOpenxQtyStr.value) instead of eval(tempOpenxQtyStr).value since the last one does basically nothing, just evaluating an object and then fetching the objects value (it doesn't eval the value itself).