Javascript: parseInt issue when it comes to math operators - javascript

I have this slider that on 'slide' grabs pricing values (string with euro symbol) from an array, later parsed (parseInt) for the html output. This works fine, on the output i get the number plus the symbol, but when I need to multiply those values (switch month pricing to anual), I loose the output, no numbers or symbol. So I guess the parseInt is working properly without a math operator...? I've serached for similar issues but I couldn't find any solution and it just got me more confused...Can anyone tell what I'm missing? The code:
var priceStarter = [
'149€',
'199€',
'249€',
'399€',
'599€',
'999€',
'Contact Us',
];
slider.on('slide', function (values, handle) {
if(jQuery(this).hasClass('active-anual')){
//ANUAL
var anualStarter = priceStarter[parseInt(handle)];
priceValueStarter.html(anualStarter * 10); //ISSUE HERE
}
else {
//MONTHLY
priceValueStarter.html(priceStarter[parseInt(handle)]); //WORKS
}
});
//TOGGLE ANUAL/MONTHLY
anual.on('click',function(){
jQuery(this).toggleClass('active-tab');
monthly.removeClass('active-tab');
slider.addClass('active-anual');
})
monthly.on('click', function () {
jQuery(this).toggleClass('active-tab');
anual.removeClass('active-tab');
slider.removeClass('active-anual');
})
}
EDIT:
This console.log(anualStarter) gives me the correct value but this console.log(anualStarter*10) gives me NaN
EDIT: based on Constantiner's answer, I get the numbers but I still loose the euro symbol and the contact us when using the operator
slider.on('slide', function (values, handle) {
if (jQuery(this).hasClass('active-anual')) {
//ANUAL
var anualStarter = priceStarter[parseInt(handle)];
priceValueStarter.html(parseInt(anualStarter )*10);
} else {
//MONTHLY
priceValueStarter.html(priceStarter[parseInt(handle)]);
}
})
;

Your priceStarter[parseInt(handle)] is a string like "249€". So you can't use anualStarter * 10 ("249€" * 10) — it is NaN. Try to use parseInt(anualStarter) * 10 instead.
A little explanation. When you try to use "249€" * 10 JavaScript engine tries to cast the string "249€" as a Number and doesn't interpret it as integer or something. So your "249€" * 10 is the same as Number("249€") * 10 and Number("249€") is NaN.
I suppose you planned to write some code like the following:
slider.on('slide', function (values, handle) {
if(jQuery(this).hasClass('active-anual')){
//ANUAL
var anualStarter = priceStarter[parseInt(handle)];
priceValueStarter.html(isNaN(parseInt(anualStarter)) ? anualStarter : parseInt(anualStarter) * 10 + "€"); //ISSUE HERE
}
else {
//MONTHLY
priceValueStarter.html(priceStarter[parseInt(handle)]); //WORKS
}
});

Related

Adding a number to a variable in a parent window

I am trying to load an existing answer and then add a number to it. The answerTotal variable has been set to the value of the recorded answer.
This then should be increasing by 12.5 each time the if statement actions. The problem is that this is not what is happening.
The number is being added on to the end of the loaded answer, for example if the load answer is 25, the output would be 2512.5 when it should be 37.5.
I have seen answers on here mentioning parseInt but it either doesnt work or im not using it correctly. parse answer
Here is what I have at the moment:
var answerTotal = 0;
window.parent.LoadAnswerReturned = function (Reference, Value) {
answerTotal = Value;
}
setTimeout(function(){
window.parent.LoadAnswer('TEST');
}, 100);
function checkAnswer(clicked) {
if(...){
...
answerTotal += 12.5
}
}
Please let me know if any more information is needed. Cheers.
It seems that the variable answerTotal is a string. You need to convert it to number using Unary Plus and then add it other number.
function checkAnswer(clicked) {
if(...){
...
answerTotal = +answerTotal + 12.5
}
}
The unexpected result is because by the type of the variable data that is string rather than number. This in turn means that string addition is performed:
"25" + "12.5" = "2512.5"
Instead, you should update you code to ensure arithemtic addition is performed instead:
function checkAnswer(clicked) {
if(...){
...
/* Use parseFloat to ensure two numbers are added, rather than a string
and a number */
answerTotal = Number.parseFloat(answerTotal) + 12.5;
}
}
You should parse your float variable, so you ensure you are using float variables:
answerTotal = parseFloat(answerTotal) + 12.5;

jquery comparing 2 integers

My submit click function is as below.
aAmt is a $ field like for eg. $45.00
a_amount is always 10000.
I am converting a_amount to $ in displayCurrencyFormat function.
I am then converting both to parseInt and doing >= comaprison and it fails. Even though aAmt is > $10000 and conition should display alert it doesnt.
$("#submitId").click(function () {
var aAmt = $("#aAmt").val();
var a_amount = "${dAmt}";
a_amount = displayCurrencyFormat(a_amount);
var pLen = $("#pOd").val();
if ((parseInt(aAmt) >= parseInt(a_amount)) && (pLen.length == 0)) {
$('#pDiv').text('Please provide a password');
$("#pOd").focus();
return false;
}
...//
});
function displayCurrencyFormat(a_amount)
{
//convert amount to currency format
var nbrAmt = Number(a_amount.replace(/[^0-9\.]+/g,""));
var fmtAmt = '$' + nbrAmt.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
return fmtAmt;
}
You should convert it into an integer-like data first, and then you can compare them.
The currency formatted input are considered as not a number format so comparing them are something like String to String comparison, not Number to Number like what you want to achieve.
Refrence link: How to convert a currency string to a double with jQuery or Javascript?
Do you know that parseInt('$10000') actually giving you "NaN"?
And as i can see here you are trying to compare integer and string...
Just try to alert aAmt and a_amount variables before you compare them and you will see what is actually going on...

Javascript Math.floor issue between specific range of numbers

I'm facing an issue with Math.floor function of javascript for the below scenario:
1) from the value betwwen 8192 and 10484,
if I type 8192.8 -> The Math.floor converts it into 8192.79
if I type 8192.88 -> The Math.floor converts it into 8192.87
if I type 8192.3 -> The Math.floor converts it into 8192.29
Strange part is that except from the range given above the function works fine.
HTML:
<div data-bind="text: popIncrease"></div>
<input type="text" data-bind="value: userInput, valueUpdate: 'afterkeydown'" />
Javascript:
var ViewModel = function () {
var _self = this;
_self.userInput = ko.observable();
_self.popIncrease = ko.computed(function () {
return parseFloat((Math.floor(_self.userInput() * 100) / 100)).toFixed(2);
});
};
ko.applyBindings(new ViewModel());
jsfiddle:https://jsfiddle.net/91z5bdy4/1/
When I changed 100 with 1000 it solved the error but I do not understand why this happened on the first place?
You can just switch to this:
return parseFloat(_self.userInput()).toFixed(2);
Working version of your jsFiddle: https://jsfiddle.net/jfriend00/5rLL04Lk/
Or, if you want to work around some of the idiosyncrasies of .toFixed(), you can use this:
return (Math.round(_self.userInput() * 100) / 100).toFixed(2);
Working jsFiddle: https://jsfiddle.net/jfriend00/xx2aj2L0/
This solution passes all three of your test cases.
It's not Math.floor() that causes the problem, it is the inexactness of the floating point arithmetic. When you multiply 8192.8 by 100, you get 819279.9999999999.
Perhaps you should just manipulate it as a string:
function floorString(str) {
var pos = str.indexOf('.');
return (pos >= 0) ? ((str + '00').slice(0, pos + 3)) : (str + '.00');
}
jsfiddle
The order of your floor/parse seems out of order to me.
Try:
return Math.floor(parseFloat(_self.userInput())).toFixed(2);
Though be aware that 1.999999999999999999999999999999 gives 2.00 using the above; this is because floating point numbers aren't able to represent all values precisely.
another one without using a Math function (2 lines without formatting)
function floorString(str) {
var matches = str.match(/([\d]+(\.[\d]{0,2}))/);
return matches === null || matches[2].length === 1 ?
(str + ".00").replace("..", ".") :
matches[2].length < 3 ?
matches[0] + "00".substr(3 - matches[2].length) :
matches[0];
}

Javascript : function checking if the answer to score as a percentage has more than 2 decimal places

I want to create a dynamic worksheet for my students, so every time they do it they see different questions. The question that I am trying to create ie, calculate the percentage if I scored X out of a total of Y.
Here are the 3 functions which work together, the first generates some numbers, calls the second, which in turn calls the third to check if it more than 2 decimal places, then if it is, the second creates a new SCORE number which repeats until it finds an answer which is 2 decimal places or less, then returns the SCORE number which works to the first, which outputs it.
I keep getting one of three outputs : undefined where the SCORE should be, no output at all, or a working question.
I cannot understand how it works sometimes, throws undefined sometimes and gives completely nothing at other times.
Any ideas.
function scorePercent()
{
var output="";
var total = Math.floor((Math.random()*99)+1);
var score = Math.floor((Math.random()*(total-1))+1);
output = output + "<div>A score of " + chkScore(score,total) + " out of " + total + ".</div></br>";
document.getElementById("qOut").innerHTML=output;
}
function chkScore(n1,n2)
{
var answ = (n1/n2)*100;
if(dps(answ)>2)
{
var scoreNew = Math.floor((Math.random()*(n2-1))+1);
chkScore(scoreNew, n2);
}
else
{
return n1;
}
}
function dps(num)
{
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(
0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0)
// Adjust for scientific notation.
- (match[2] ? +match[2] : 0));
}
You have a recursive function in your chkScore, but you're not return-ing the results from the "deeper" iterations.
Try this:
function chkScore(n1,n2){
var answ = (n1/n2)*100;
if(dps(answ)>2) {
var scoreNew = Math.floor((Math.random()*(n2-1))+1);
return chkScore(scoreNew, n2); // <-- return that.
} else {
return n1;
}
}
The missing return there, resulted in the function sometimes not returning anything.
The "deeper" iterations will return their value only 1 "level" up, so that "level" will have to pass it through, if you know what I mean.

JavaScript function to add two numbers is not working right

My code in HTML takes a user input number in, and it does a calculation and then displays the output. The user chosen input is put into a formula and the result of the formula is added to the user input number, but when it adds the two number together it's adding a decimal spot.
For example, if the number 11 is chosen, the result of Rchange is 0.22, so .22 is then added 11 to be 11.22 for newResistance, but instead it is displaying the value as 110.22 instead.
function calc(form) {
if (isNaN(form.resistance.value)) {
alert("Error in input");
return false;
}
if (form.resistance.value.length > 32) {
alert("Error in input");
return false;
}
var Rchange = .01 * 2 * form.resistance.value;
var newResistance = (form.resistance.value + Rchange);
document.getElementById("newResistance").innerHTML = chopTo4(newResistance);
}
function chopTo4(raw) {
strRaw = raw.toString();
if (strRaw.length - strRaw.indexOf("0") > 4) strRaw = strRaw.substring(0, strRaw.indexOf("0") + 5);
return strRaw;
}
HTML DOM element properties are always strings. You need to convert them to numbers in your usage.
parseInt(form.resistance.value);
parseFloat(form.resistance.value);
+form.resistance.value;
(Any of the three will work; I prefer the first two (use parseInt unless you're looking for a float).)
Try newResistance = +form.resistance.value + Rchange;. This will convert it to a number.
It's because it's treating the values as a string.
form.resistance.value + Rchange are both strings, so it's appending it.
Use the parseInt JavaScript method to get the decimal version.

Categories

Resources