Make document getElementById as Int - javascript

I have this code that add numbers and prints it in input text for readonly
document.getElementById('total') += parseInt(tot);
but it JUST adds numbers as sting , for example when add 8 and 10 that would be 18 but it prints them as 810 , why ?

Use the parseInt() function to both of them:
document.getElementById('total').value = parseInt(tot)+parteInt(document.getElementById('total').value);

Just parse the value from string to integer like this
var x = document.getElementById('total');
x.value = parseInt(x.value) + parseInt(tot);
Or use parseFloat() if you have decimal numbers.

You can try this:
var elem = document.getElementById('total');
elem.value = +elem.value + parseInt(tot);
The + sign force the type to number.

Related

How to convert a string to number

I can't figure it out how to convert this string 82144251 to a number.
Code:
var num = "82144251";
If I try the code below the .toFixed() function converts my number back to a string...
Question update:
I'm using the Google Apps Script editor and that must be the issue...
num = parseInt(num).toFixed() // if I just do parseInt(num) it returns 8.2144251E7
You can convert a string to number using unary operator '+' or parseInt(number,10) or Number()
check these snippets
var num1a = "1";
console.log(+num1a);
var num1b = "2";
num1b=+num1b;
console.log(num1b);
var num3 = "3"
console.log(parseInt(num3,10));
var num4 = "4";
console.log(Number(num4));
Hope it helps
It looks like you're looking for the Number() functionality here:
var num = "82144251"; // "82144251"
var numAsNumber = Number(num); // prints 82144251
typeof num // string
typeof numAsNumber // number
You can read more about Number() here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
Hope this helps!
No questions are dumb.
a quick answer:
to convert a string to a number you can use the unary plus.
var num = "82144251";
num = +num;
Doing num = +num is practically the same as doing num = num * 1; it converts the value in a to a number if needed, but after that it doesn't change the value.
var num = "82144251";
num = parseInt(num).toFixed()
console.log(num, typeof num); // string
num = parseFloat(num);
console.log(num, typeof num); // number
var intNum = parseInt("82144251", 10); // intNum is number
I use num-0, since it is easier for inline use.

Adding values in javascript [duplicate]

This question already has answers here:
Plus Arithmetic Operation
(7 answers)
Closed 8 years ago.
I am trying to add up the 2 values (bold) that are inputed by the user but instead of adding then mathematically (100+1 = 101) it adds them like this (100+1 = 1001).
$('#inputcost').keyup(function(){
var price = $(this).val();
});
function checkboxcost() {
var sum = 0;
var gn, elem;
for (i=0; i<2; i++) {
gn = 'extra'+i;
elem = document.getElementById(gn);
if (elem.checked == true) { sum += Number(elem.value); }
}
**var total = (price.value + sum.toFixed(2));
document.getElementById('totalcost').value = "$" + total;**
}
</script>
<input id="totalcost" disabled/>
The problem is, as you suspect, in this line:
var total = (price.value + sum.toFixed(2));
The problem is that .toFixed converts the number to a string for display. So you are trying to add a string to a number, which results in concatenation, not addition.
You want to add the numbers together, then display the sum:
var total = (price.value + sum).toFixed(2);
With that said, I'm not sure where price.value is coming from, so it's possible that's a string too. In which case, convert it with the unary plus + operator:
var total = (+price.value + sum).toFixed(2);
Its treating price.value as String so convert that string to number like:
var total = (Number(price.value) + sum.toFixed(2));
it seems string addition is taking place.
So try converting string numbers to integer using parseInt() like:
var x = parseInt("1")
var y = parseInt("2")
var z = x + y
Try parseInt(price.value) + ...
It's because the types of the operands are strings and the + operator for two strings does concatenation, not addition.
If you convert them to numbers then you'll get a number result:
"1" + "2" == "12"
parseFloat("1") + parseFloat("2") == 3

alerts that concatenate rather than add

super remedial question that I just cant quite figure out (new to javascript).
I need to find a way to prompt for a string of text and then alert that string of text 3 times. I have tried the + sign in my alert but that would give me NaN or just an addition rather than just the string. For example if I input 2 it would return 6 rather than 222 which I need.
One way is to include strings in your concatenation:
alert(num+''+num+''+num);
Another is to convert the number to a string first:
var str = num.toString();
alert(str+str+str);
The whole thing would be:
var num = +prompt("Enter a number");
var str = num.toString();
alert(str + str + str);
Just include a string somewhere in between:
2+''+2+2
E.g.
var input = prompt('type something'), result = '';
for(var i = 0; i < 3; i++)
result += input;
console.log(result);
http://jsfiddle.net/35tp3/
Try this:
var number = 2, repeat = 3;
Array(repeat+1).join( number );
That will output "222"
If you want to add a space:
Array(repeat+1).join(" " + number).trim();
Which will output "2 2 2"

Stop javascript automatically casting from decimal to string

I have the following piece of code:
if(netAnnualBilling == null){
netAnnualBilling = 0;
parseFloat(netAnnualBilling);
}
parseFloat(netAnnualBilling);
annualBillingCount = (annualBillingCount + netAnnualBilling);
parseFloat(annualBillingCount);
My two variables netAnnualBilling and annualBillingCount are both of type numbers. However, when I get to this line:
annualBillingCount = (annualBillingCount + netAnnualBilling);
javascript seems to turn annualBillingCount into type String and appends the two numbers together instead of adding or subtracting as its supposed to. Example:
annualBillingCount = 0;
netAnnualBilling = -1403.30
The result of the above code will show annualBillingCount to be equal to : 0-1403.80
I've tried ParseFloat every time these variables pop up but I'm not having any luck. What's going on?
If you want to make sure the variables are used as numbers, you can simply prepend the unary plus operator:
annualBillingCount = +annualBillingCount + +netAnnualBilling;
will force each operand to be treated as a number.
EDIT Heres a basic fiddle showing the addition of two strings with varying uses of the unary casting, using the code below:
var onetwo = "12";
var threefour = "34";
alert(onetwo + threefour); // string + string, so "12" + "34" = "1234"
alert(+onetwo + threefour); // number + string, so 12 + "34" = "12" + "34" = "1234"
alert(onetwo + +threefour); // string + number, second will be coerced back to string, so "12" + "34" = "1234"
alert(+onetwo + +threefour); // number + number, so 12 + 34 = 46
parseFloat() doesn't change the value, it returns the casted value. You need:
netAnnualBilling = parseFloat(netAnnualBilling)
Try this:
if(netAnnualBilling == null) {
netAnnualBilling = 0;
}
netAnnualBilling = parseFloat(netAnnualBilling);
annualBillingCount = parseFloat(annualBillingCount);
annualBillingCount += netAnnualBilling;

Remove/ truncate leading zeros by javascript/jquery

Suggest solution for removing or truncating leading zeros from number(any string) by javascript,jquery.
You can use a regular expression that matches zeroes at the beginning of the string:
s = s.replace(/^0+/, '');
I would use the Number() function:
var str = "00001";
str = Number(str).toString();
>> "1"
Or I would multiply my string by 1
var str = "00000000002346301625363";
str = (str * 1).toString();
>> "2346301625363"
Maybe a little late, but I want to add my 2 cents.
if your string ALWAYS represents a number, with possible leading zeros, you can simply cast the string to a number by using the '+' operator.
e.g.
x= "00005";
alert(typeof x); //"string"
alert(x);// "00005"
x = +x ; //or x= +"00005"; //do NOT confuse with x+=x, which will only concatenate the value
alert(typeof x); //number , voila!
alert(x); // 5 (as number)
if your string doesn't represent a number and you only need to remove the 0's use the other solutions, but if you only need them as number, this is the shortest way.
and FYI you can do the opposite, force numbers to act as strings if you concatenate an empty string to them, like:
x = 5;
alert(typeof x); //number
x = x+"";
alert(typeof x); //string
hope it helps somebody
Since you said "any string", I'm assuming this is a string you want to handle, too.
"00012 34 0000432 0035"
So, regex is the way to go:
var trimmed = s.replace(/\b0+/g, "");
And this will prevent loss of a "000000" value.
var trimmed = s.replace(/\b(0(?!\b))+/g, "")
You can see a working example here
parseInt(value) or parseFloat(value)
This will work nicely.
I got this solution for truncating leading zeros(number or any string) in javascript:
<script language="JavaScript" type="text/javascript">
<!--
function trimNumber(s) {
while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
return s;
}
var s1 = '00123';
var s2 = '000assa';
var s3 = 'assa34300';
var s4 = 'ssa';
var s5 = '121212000';
alert(s1 + '=' + trimNumber(s1));
alert(s2 + '=' + trimNumber(s2));
alert(s3 + '=' + trimNumber(s3));
alert(s4 + '=' + trimNumber(s4));
alert(s5 + '=' + trimNumber(s5));
// end hiding contents -->
</script>
Simply try to multiply by one as following:
"00123" * 1; // Get as number
"00123" * 1 + ""; // Get as string
1. The most explicit is to use parseInt():
parseInt(number, 10)
2. Another way is to use the + unary operator:
+number
3. You can also go the regular expression route, like this:
number.replace(/^0+/, '')
Try this,
function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
var str =ltrim("01545878","0");
More here
You should use the "radix" parameter of the "parseInt" function :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FparseInt
parseInt('015', 10) => 15
if you don't use it, some javascript engine might use it as an octal
parseInt('015') => 0
If number is int use
"" + parseInt(str)
If the number is float use
"" + parseFloat(str)
const number = '0000007457841';
console.log(+number) //7457841;
OR number.replace(/^0+/, '')
Regex solution from Guffa, but leaving at least one character
"123".replace(/^0*(.+)/, '$1'); // 123
"012".replace(/^0*(.+)/, '$1'); // 12
"000".replace(/^0*(.+)/, '$1'); // 0
I wanted to remove all leading zeros for every sequence of digits in a string and to return 0 if the digit value equals to zero.
And I ended up doing so:
str = str.replace(/(0{1,}\d+)/, "removeLeadingZeros('$1')")
function removeLeadingZeros(string) {
if (string.length == 1) return string
if (string == 0) return 0
string = string.replace(/^0{1,}/, '');
return string
}
One another way without regex:
function trimLeadingZerosSubstr(str) {
var xLastChr = str.length - 1, xChrIdx = 0;
while (str[xChrIdx] === "0" && xChrIdx < xLastChr) {
xChrIdx++;
}
return xChrIdx > 0 ? str.substr(xChrIdx) : str;
}
With short string it will be more faster than regex (jsperf)
const input = '0093';
const match = input.match(/^(0+)(\d+)$/);
const result = match && match[2] || input;
Use "Math.abs"
eg: Math.abs(003) = 3;
console.log(Math.abs(003))

Categories

Resources