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

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

Related

JavaScript program to convert binary to decimal

I am trying to make a program which is able to do both decimal to binary and binary to decimal conversions.
I am having trouble with the binary to decimal portion of the code. Forgive me as I know the coding is quite incomplete but I can't figure out where I am going wrong.
Currently I am getting partially correct output in the calculation field (ex. "there is a 1 in the value of (2^0)" and "there is a 2 in the value of (2^1)").
However, when I type 11 as decimal the calculation field is repeating the code twice
(ex. "there is a 1 in the value of (2^0)","there is a 2 in the value of (2^1)","there is a 1 in the value of (2^0)", "there is a 2 in the value of (2^1)").
Obviously it should only give those values once per number.
Also the output field for the actual binary number is incorrect as well, and some of the variables aren't utilized/not needed, but I have been trying to fix the problem of repeating values first before I worked on that.
Any help would be much appreciated!!
function convertByArray(bval) {
var rB = new Array();
var outstr = "";
var p, t, a, o;
o = 0;
for(var i=0; i<bval.length; i++) {
var b = bval.charCodeAt(i);
t = 2;
p = i;
a = t ** p;
if(a === t ** p) {
outstr += a;
}
var bV = b;
$("txtCalc").value += "There is a " + a + " in the value " + "(" + t + "^" + p + ")" + "\n";
o += 1;
b = bV;
$("txtOut").value = outstr;
}
}
You can simply your code if you access the most-significant bit of the bit-string by taking the length (minus one) and subtracting it from the current position. You can access string characters like an array.
var $txtCalc = $(".txtCalc");
var $txtOut = $(".txtOut");
binaryToDecimal("10010101"); // 149
function binaryToDecimal(bval) {
var base = 2, result = 0;
for (var pos = 0; pos < bval.length; pos++) {
var bit = +bval[(bval.length - 1) - pos];
if (bit === 1) {
result += base ** pos;
}
var message = "There is a " + bit + " in the position (" + base + "^" + pos + ")";
$txtCalc.val($txtCalc.val() + message + "\n");
}
$txtOut.val(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="txtOut" />
<br />
<textarea class="txtCalc" rows="10" cols="60"></textarea>
Alternatively, you can simply your program to the following. In JavaScript, you can parse any number in any base and format to another base.
var $txtOut = $(".txtOut");
binaryToDecimal("10010101"); // 149
function convertFromBaseToBase(number, fromBase, toBase) {
return parseInt(number, fromBase).toString(toBase);
}
function binaryToDecimal(bval) {
$txtOut.val(convertFromBaseToBase(bval, 2, 10));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="txtOut" />

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))

JQuery setting a number format

I'm using JQuery and I'm having a problem trying to sort out how to increase a number.
The record number is something like 1364-14-1234.
The number format works like this:
1364 - Member number
14 - Year in 2 digit format
1234 - in the number which needs to be increased.
The problem is how do I add a leading zero to the number to keep a 4 digit number if the number is 0123.
<div id="member_id">1364-14-0001</div>
var data = $('#member_id').text();
var arr = data.split('-');
var num = arr[2];
num++;
$("#member_id").html(arr[0] + " - " + arr[1] + " - " + num);
My JSfiddle
Something like this maybe
function pad(numb, len) {
while (numb.toString().length < len) numb = '0' + numb;
return numb;
}
$('#member_id').text(function(_, txt) {
var arr = txt.split('-'),
len = arr[2].length;
arr[2] = pad(+(arr[2]) + 1, len);
return arr.join('-')
});
FIDDLE

javascript timer with comma [duplicate]

This question already has answers here:
How to format numbers as currency strings
(67 answers)
Closed 9 years ago.
I want to display the dollar timer which goes from 1 to 2500. When the timer increases to 1000, I want to display it as $1,000 instead of $1000. I want commas in thousands place.Could someone help me with this JavaScript.
Thanks.
You could easily do this with a regular expression.
var friendlyNum = (num + "").replace(/^(\d)(\d{3})$/, "$1,$2");
Note that this will only handle 1000 places.
How it works is an exercise to the reader. For learning how they work, stat here.
Even though it's been written a thousand times, I felt like writing some JS.
var addCommas = function(number) {
number = '' + number;
var negative = false;
if (number.match(/^\-/)) {
negative = true;
}
number = number.replace(/[^0-9\.]/g, '');
number = number.split('.');
var before = number.shift()
, after = number.join('');
for (var i = (before.length - 3); i > 0; i -= 3) {
before = before.substr(0, i) + ',' + before.substr(i)
}
return (negative ? '-' : '') + before + (after ? '.' + after : '');
}
// 1,000.00
addCommas(1000.00);
// -1,234,567,890
addCommas('-1234567890');
Below is the approach to convert number format (comma separated)
HTML :-
<input type="text" onkeyup="convertNumberFormat(this.value)" />
JavaScript:-
function convertNumberFormat(inputValue)
{
inputValue = inputValue.toString();
inputValue = inputValue.replace( /\,/g, "");
var x = inputValue.split( '.' );
var intValue = x[0];
var floatValue = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while ( rgx.test(intValue) ) {
intValue = intValue.replace( rgx, '$1' + ',' + '$2' );
}
alert(intValue + floatValue);
}
In HTML template I am calling this function at "onkeyup" event.
you just need to call "convertNumberFormat" function whenever you want to validate your input value and pass current inserted value...
Example:-
convertNumberFormat('$2500');
Output:-
'$2,500' // in alert.
hope this can help you...

parseInt does not work as expected

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);

Categories