parseInt does not work as expected - javascript

The answer may be obvious but I don't see
I have a JavaScript object virtualTable. I write :
parseInt(virtualTable["resource_" + resourceId])
it returns NaN
I check virtualTable["resource_" + resourceId] with an alert and the answer is "690"
If I alert parseInt("690") it works fine and returns 690
What is wrong then?
the whole code :
if(!virtualTable.hasOwnProperty("resource_" + resourceId)) {
virtualTable["resource_" + resourceId] = "\"" + minutesToFill + "\"";
}
var timeForTarget = (target.end.getTime() - target.start.getTime()) / 60000;
var timeInVirtualTable;
var tooltipInTarget
if(virtualTable["resource_" + resourceId].indexOf("_") == -1) {
timeInVirtualTable = parseInt(virtualTable["resource_" + resourceId]);
tooltipInTarget = "";
} else {
timeInVirtualTable = parseInt(virtualTable["resource_" + resourceId].substring(0, virtualTable["resource_" + resourceId].indexOf("_")));
tooltipInTarget = virtualTable["resource_" + resourceId].substring(virtualTable["resource_" + resourceId].indexOf("_"));
}

Per your statement,
I check virtualTable["resource_" + resourceId] with an alert and the
answer is "690"
I'm assuming that the value inside virtualTable["resource_" + resourceId] is literally "690", including the quotes. Because of this, it's NaN, or, not-a-number (due to the leading double-quote).
If this will be common input, you can strip the double-quotes from your value before (or during) the call to parseInt using replace():
var value = virtualTable["resource_" + resourceId].replace(/"/g, '');
var number = parseInt(value);
or:
var number = parseInt(virtualTable["resource_" + resourceId].replace(/"/g, ''));
EDIT (parseInt()'s base):
Building on a comment, you should also remember to always specify the numeric-base to parse the input to. In your case, you want base-10 (or "decimal"). This is specified as the second parameter to parseInt():
var number = parseInt(value, 10);
or
var number = parseInt(virtualTable["resource_" + resourceId].replace(/"/g, ''), 10);

Related

Am I correct about .toFixed() and decimals?

I gave an example of using .tofixed() with math, functions, and arrays, to a beginner coder friend who has been reviewing these topics in his class.
const bananaX = 9;
const bananaY = 2.9768;
bananaArray = [bananaX , bananaY];
console.log("X before array = " + bananaX);
console.log("Y before array = " + bananaY + '\n')
console.log("X,Y after array = " + bananaArray + '\n')
console.log("Value of X in array: " + bananaArray[0]+ '\n')
console.log("Value of Y in array: " + bananaArray[1]+ '\n')
function bananaDivision (bananaArray){
console.log("Value of X after function = " + bananaX);
console.log("Value of Y after function = " + bananaY + '\n')
let bananaDivided = Math.abs(bananaX/bananaY );
console.log (`X divided by Y = + ${bananaDivided}` + '\n')
let bananaFixed = bananaDivided.toFixed(2);
console.log("After using .toFixed(2) : " + bananaFixed + '\n');
};
bananaDivision();
They were understanding and following along no problem.
Then they asked me - "What if we put a decimal in the .toFixed ?"
So I ran:
const bananaX = 9;
const bananaY = 2.9768;
bananaArray = [bananaX , bananaY];
console.log("X before array = " + bananaX);
console.log("Y before array = " + bananaY + '\n')
console.log("X,Y after array = " + bananaArray + '\n')
console.log("Value of X in array: " + bananaArray[0]+ '\n')
console.log("Value of Y in array: " + bananaArray[1]+ '\n')
function bananaDivision (bananaArray){
console.log("Value of X after function = " + bananaX);
console.log("Value of Y after function = " + bananaY + '\n')
let bananaDivided = Math.abs(bananaX/bananaY );
console.log (`X divided by Y = + ${bananaDivided}` + '\n')
let bananaFixed = bananaDivided.toFixed(2);
let bananaFixed1 = bananaDivided.toFixed(.69420);
let bananaFixed2 = bananaDivided.toFixed(1.69420);
console.log("After using .toFixed(2) : " + bananaFixed + '\n');
console.log("After using .toFixed(.69420) : " + bananaFixed1 + '\n');
console.log("After using .toFixed(1.69420) : " + bananaFixed2 + '\n');
};
bananaDivision();
I explained it as that .toFixed is looking at the first number within the () and that the decimals are ignored.
Am I correct? For my own curiousity, is there a crazy way to break .toFixed() so that it actually uses decimals? I'm experimenting atm but wanted to know if someone already figured that out.
I explained it as that .toFixed is looking at the first number within the () and that the decimals are ignored.
This would be correct. That is essentially what happens.
For full correctness, the input of toFixed() will be converted to an integer. The specification states that the argument must first be converted to a number - NaN will be converted to a zero. Numbers with a fractional part will be rounded down.
Which means that if you pass any number, you essentially get the integer part of it.
It also means that non-numbers can be used:
const n = 3;
console.log(n.toFixed("1e1")); // 1e1 scientific notation for 10
You're close, since toFixed() expects an integer it will handle converting decimal numbers before doing anything else. It uses toIntegerOrInfinity() to do that, which itself uses floor() so the number is always rounded down.
Most of Javascript handles type conversion implicitly, so it's something you should really understand well if you don't want to run into problems. There's a free book series that explains that concept and a lot of other important Javascript knowledge very well, it's called You Don't Know JS Yet.
just a demo how .tofixed works !!!!!!
function roundFloat(x, digits) {
const arr = x.toString().split(".")
if (arr.length < 2) {
return x
}else if(arr[1] === ""){
return arr[0]
}else if(digits < 1){
return arr[0]
}
const st = parseInt(x.toString().split(".")[1]);
let add = false;
const rudgt = digits
const fX = parseInt(st.toString().split("")[rudgt]);
fX > 5 ? add = true : add = false
nFloat = parseInt(st.toString().split("").slice(0, rudgt).join(""))
if (add) {
nFloat += 1
}
const repeat0 = (() => {
if (rudgt - st.toString().length < 0) {
return 0
}
return rudgt - st.toString().length
})()
const output = x.toString().split(".")[0] + "." + nFloat.toString() + "0".repeat(repeat0);
return output
}
console.log(roundFloat(1.200, 2))

printing only even numbers between two numbers that are called in Javascript

function evenNumbers(minNumber, maxNumber){
var str = minNumber;
for (i=minNumber; i<=maxNumber; i++){
if (minNumber%2 ==0){
str += ',' + i;
}
}
return str;
}
console.log('evenNumbers(4,13) returns: ' + evenNumbers(4,13));
console.log('evenNumbers(3,10) returns: ' + evenNumbers(3,10));
console.log('evenNumbers(8,21) returns: ' + evenNumbers(8,21));
So, what I want the code to do is that in the given numbers in console.log,
for example, (4,13) it should print all the numbers that are EVEN between 4 and 13. However, instead of giving all the even numbers, the function gives me all the numbers that are between 4,13. How Could I fix the problem?
p.s is there any strcmp in javascript?
Wrong variable in if statement inside for loop.
if (minNumber%2 ==0){
str += ',' + i;
}
Should be
if (i%2 ==0){
str += ',' + i;
}
I presume you want to show the numbers between the min and max but not including either the min or max. In other words, evenNumbers(4,8) should just show 6. I also presume that both the min and max values will be integers.
I put all the logic in the for loop parameters, with the for loop body just placing those numbers and a comma into the output string. The final return value removes the last comma.
function evenNumbers(minNumber, maxNumber){
let str = '';
for (let i = Math.ceil((minNumber + 0.5) / 2) * 2; i < maxNumber; i += 2) {
str += `${i},`;
}
return str.slice(0,-1);
}
console.log('evenNumbers(4,13) returns: ' + evenNumbers(4,13));
console.log('evenNumbers(3,10) returns: ' + evenNumbers(3,10));
console.log('evenNumbers(8,21) returns: ' + evenNumbers(8,21));
console.log('evenNumbers(-8,5) returns: ' + evenNumbers(-8,5));
console.log('evenNumbers(-7,-2) returns: ' + evenNumbers(-7,-2));
console.log('evenNumbers(5,6) returns: ' + evenNumbers(5,6));
console.log('evenNumbers(10,2) returns: ' + evenNumbers(10,2));

JavaScript - concat two numbers and treat the result as a number [duplicate]

This question already has answers here:
How to convert a string to an integer in JavaScript
(32 answers)
Closed 6 years ago.
here's the code I'm struggling with. I'd like to concat the two inputs together and keep the result as an integer (number in JS's case).
var secsVal = -1;
function valueAssign(i) {
if (secsVal == -1){
document.getElementById("countdown").value = i;
document.getElementById("countdown").innerHTML = (i);
secsVal = i;
}
else {
secsVal = "" + secsVal + i;//concatenating first value of i to the second.
secsVal = secsVal.map(Number);//trying to convert back to num, but I think map() needs to see an array, which I don't think I got here.
document.getElementById("countdown").value = secsVal;
document.getElementById("countdown").innerHTML = (secsVal);//I want to replace the first displayed digit here, with the new (concatenated) number.
}
}
It makes no sense to use a number for a value in an input tag. The type is always a string.
To convert to number use either Number or an unary +
secsVal = Number(secsVal);
or
secsVal = +secsVal;
Try this
secsVal = +("" + secsVal + i);
secsVal = Number('' + secsVal + i) // explicit cast to number
secsVal = +('' + secsVal + i) // implicit cast to number
secsVal = parseInt('' + secsVal + i) // explicit cast to integer
secsVal = ~~('' + secsVal + i) // implicit cast to integer
Simply use +secsVal
var secsVal = -1;
function valueAssign(i) {
if (secsVal == -1){
document.getElementById("countdown").value = i;
document.getElementById("countdown").innerHTML = (i);
secsVal = i;
}
else {
secsVal = "" + secsVal + i;
console.log(typeof secsVal);//secsVal is a string
secsVal = +secsVal;
console.log(typeof secsVal); //secsVal is now a number
document.getElementById("countdown").value = secsVal;
}
}
<input type="number" id="countdown"/>
<button onclick="valueAssign(5)">Click</button>
How about parsing the String?
"The parseInt() function parses a string and returns an integer."
http://www.w3schools.com/jsref/jsref_parseint.asp

Greater than returns wrong value on numbers lower then 100

This is my first JavaScript project, so I'm sure this code isn't pretty, and could be written in a much better way, but that aside, I've encountered a problem I just don't understand. I'm sure it's just a bug I've made myself, but I just simply can't find it.
The '>' (greater than) operator works fine on numbers over 100, but stops working when it gets to 100. For some reason 100 > 99 returns false?
https://jsbin.com/vigocu/edit?console,output
Move the slider to the right, and then slowly to the left, and you will see it returning "true" until it reaches 100. From there it returns "false"
function getSliderInput(inputSliderId) {
var backSwingArray = [100];
var downSwingArray = [];
document.querySelector('#' + inputSliderId).addEventListener('input', fillArray , false);
function fillArray() {
if (isNaN(downSwingArray[downSwingArray.length - 1]) && backSwingArray[backSwingArray.length - 1] < this.value) {
backSwingArray.push(this.value);
} else if (downSwingArray[downSwingArray.length - 1] > this.value || isNaN(downSwingArray[downSwingArray.length - 1])){
console.log('Is ' + downSwingArray[downSwingArray.length - 1] + ' > ' + this.value + ' return ' + (downSwingArray[downSwingArray.length - 1] > this.value));
downSwingArray.push(this.value);
} else {
console.log('Is ' + downSwingArray[downSwingArray.length - 1] + ' > ' + this.value + ' return ' + (downSwingArray[downSwingArray.length - 1] > this.value));
return;
}
}
}
value on input elements is always a string. While that won't be a problem initially, when you're comparing this.value to the 100 you've put in the array to start with, you then push this.value into the array as-is (as a string). That means later, you'll end up comparing that stored string with another this.value value, which is also a string. If either operand to > is a number, it will coerce the other operand to number (the way + does, see below), but if both operands are strings, it will do a lexical comparison, not a numeric one, and "100" is indeed < "99" because "1" is < "9".
So you want to convert this.value to a number early on, and then use that number both when comparing and when pushing into your array. You have many ways to do that:
The unary + will require the entire string to be a valid number, but will treat "" as 0; it will also treat strings starting with 0x as hexadecimal
var num = +this.value;
// or perhaps
var num = this.value === "" ? NaN : +this.value;
// or even
var str = this.value.trim(); // .trim can be shimmed on obsolete browsers
var num = str === "" ? NaN : +str;
parseInt(..., 10) (the 10 is specifying the radix [number base] to use) will allow garbage at the end of the string, treat "" as NaN, and treat any string prefixed with 0x as 0 (since it stops at the first invalid character)
var num = parseInt(this.value, 10);
Number(...) does what + does
var num = Number(this.value); // or variations above on +

What is the usage of adding an empty string in a javascript statement

I see an empty string ('' or "") used in many JavaScript statements but not sure what does it stand for.
e.g. var field = current.condition_field + '';
Can someone please clarify?
Type Casting.
It converts the type to string
If variable current.condition_field is not of string type, by adding '' using + operator at the end/beginning of it converts it to string.
var field = current.condition_field + '';
So, field is always string.
Example
var bool = true; // Boolean
var str = bool + ''; // "true"
document.write('bool: ' + typeof bool + '<br />str: ' + typeof str);
var num = 10; // Numeric
var str = num + ""; // "10"
document.write('<br /><br />num: ' + typeof num + '<br />str: ' + typeof str);
Thanks to #KJPrice:
This is especially useful when you want to call a string method(Method defined on string prototype) on that variable.
(myVar + '').toLowerCase();

Categories