Code example:
var string = "7"
console.log(string - 1) // I would want to output 6.
The variable is a string since its taken from parsed html code, and subtract 1 for a 0 index character count.
let a = "10"
console.log(Number(a) - 1) // output 9
Number() returns a number so you can either store it in a variable or directly subtract 1 from it
First, cast the string to an integer using the parseInt() or Number() functions.
For your case, use parseInt(string, 10) or Number(string). You can set it equal to a new variable called num.
Then, simply just console.log(num-1). If you want, you can just console.log(parseInt(string, 10)-1) or console.log(Number(string)-1) directly.
it's automatically done by javaScript.
Related
This question already has answers here:
How to force JS to do math instead of putting two strings together [duplicate]
(11 answers)
Closed 3 years ago.
I want to take a number input (id="number") and save it as "x". Then make another variable, "y", that is 5% of "x". And then I want to add them together and save the result in a variable called "result".
Let's say that x = 100. Then y = 5. If I would just alert "y" it would alert the number 5 which is correct but the problem is that when I try to alert "result" (x+y) it alerts 1005 (it doesn't add the numbers just write them next to each other).
let x = document.getElementById("number");
let y = x*0.05;
var result = x+y;
alert(result);
Fist get value and so convert it to number:
Change :
var x = document.getElementById("number")
to :
var x = parseInt( document.getElementById("number").value )
Note : You must convert the input to a number even if type property be equal with number.
function fun() {
var x = document.getElementById('number').value;
console.log( typeof x)
var y = parseInt(document.getElementById('number').value);
console.log( typeof y)
}
<input type="number" id="number">
<button onclick="fun()">Go..</button>
you need a value for doing some calculation. so,
var x = document.getElementById("number").value;
"+" operator will concatenate if string value exist. var x is string value but automatic type casting will occur when var y=x*0.05. so you must cleary declaire "x is number" via parseInt().
var x = parseInt(document.getElementById("number").value);
Now "+" operator will work as you expected.
What's going on is x+y is performing string concatenation, not integer addition--which is what you want.
// String concatenation
console.log("100" + "5"); // outputs "1005"
// Integer Addition
console.log(100 + 5); // outputs "105"
That's the problem, but what's the solution?
The solution is to force integer addition with something like parseInt() (as Ehsan mentioned)
var x = parseInt( document.getElementById("number").value );
Worth noting is the fact that Ehsan uses document.getElementById("number").value, instead of document.getElementById("number")
This forces x to be an int, which will allow x+y to perform integer addition.
P.S. I should also note part of the reason for your problem is related to the fact that document.getElementById("number").value is a string, forcing a type conversion to take place
Addition ‘+’ concatenates strings
Almost all mathematical operations convert values to numbers. A notable exception is addition +. If one of the added values is a string, the other one is also converted to a string.
Then, it concatenates (joins) them:
alert( 1 + '2' ); // '12' (string to the right)
alert( '1' + 2 ); // '12' (string to the left)
This only happens when at least one of the arguments is a string. Otherwise, values are converted to numbers.
Meaning that one of the operands (again, document.getElementById("number").value is a string) in an addition operation being a string forces both to become strings and get concatenated.
I want to Convert Ordinal String to its number
e.g
"1st" to 1
"2nd" to 2
"3rd" to 3
...
Tried this function but return its ordinal, not the number
function nth(n){return["st","nd","rd"][((n+90)%100-10)%10-1]||"th"}
it should be the inverse of this function
just use parseInt
console.log(parseInt("1st"))
You can remove the last two characters because suffix has constant length.
function toNum(str) {
return parseInt(str.substring(0, str.length - 2));
}
console.log(toNum("1st"));
Simply Extract Numerical Values From The String using parseInt()
parseInt("1st");
This will extract 1 i.e. Integer from the String
You can also use the function match(...) with a Regular Expression /[0-9]+/.
console.log("3rd".match(/[0-9]+/)[0]) // -> 3
console.log("52381st".match(/[0-9]+/)[0]) // -> 52381
Just doing "3rd".match(/[0-9]+/) returns an object with a bit of useful data, but just accessing the property [0] will give you the output you're looking for (if you don't want to do parseInt like the other answers are mentioning haha).
I am storing -ve and non-sign integer in Database,to depict before i.e. -ve value or after i.e. no sign from some particular reference point.
for e.g. on webpage I would show -5 as before 5 days before separation Date. How to conver that -5 into 5 . Although one way could be to get a substring of -5,but that's a naive one. Is there any better method?
You can simply use Math.abs() which returns the absolute value of a number.
Math.abs(-5)
Update: Actually I missed it. Even if it is a string, math.abs() converts automatically to number.
Math.abs(-5) //returns 5
Math.abs('-5') //returns 5
please use Math.abs(-16) to get only 16. Otherwise you could create a function that returns positive value, inside the function set logic that if input argument is positive, return it otherwise multiply with -1 and then return (in case you dont want to use Math.abs() this predefined function. any issues ?
You need to use Absolute function from Math header.
var num = -20;
num = Math.abs(num);
This will convert the number to absolute value (ie.) positive number.
Which rule do I have to follow when extracting numbers out of DOM and calcluation with them? How does javascript knows that a value is a number or not? Should I always use parseInt?
Given following Code:
HTML
<div id="myvalue">5</div>
<div id="withParseInt"></div>
<div id="withoutParseInt"></div>
<div id="withoutParseIntButIncrement"></div>
JS & jQuery:
var value = $('#myvalue').text();
$('#withParseInt').text(parseInt(value) + 1);
$('#withoutParseInt').text(value + 1);
$('#withoutParseIntButIncrement').text(value++);
Gives following output:
5
6
51
5
Fiddle: http://jsfiddle.net/ytxKU/3/
The .text() method will always return a string. Some operators, like the + operator, are overloaded to perform both arithmetic and string operations. In the case of strings, it performs concatenation, hence the "51" result.
If you have a string and need to use a non-coercing operator, you will have to use parseInt (or some other method of converting to a number).
However, the * operator for example implicity performs this coercion, so you wouldn't need the parseInt call in that situation (see an updated fiddle for example).
Note that the increment ++ operator does coerce its operand, but you've used the postfix operator so it won't have any effect. Use the prefix operator and you can see it working:
$('#withoutParseIntButIncrement').text(++value);
So, to summarise:
// Parses string to number and adds 1
$('#withParseInt').text(parseInt(value) + 1);
// Coerces number 1 to string "1" and concatenates
$('#withoutParseInt').text(value + 1);
// Implicity coerces string to number, but after it's been inserted into the DOM
$('#withoutParseIntButIncrement').text(value++);
// Implicity coerces string to number, before it's been inserted into the DOM
$('#withoutParseIntButIncrement').text(++value);
// Implicity coerces to number
$('#withoutParseIntButMultiply').text(value * 2);
Side note: it's considered good practice to always pass the second argument (the radix) to parseInt. This ensures the number is parsed in the correct base:
parseInt(value, 10); // For base 10
One and only rule:
Every value that you retrieve from the DOM is a string.
Yes, you should always use parseInt() or Number() to be on the safe side. Otherwise Javascript will decide what to do with it
The value itself is a string
Using operator + will concatenate two strings
Using operator - will calculate the numerical difference
...
It's always good to use parseInt just to be on the safe side, especially as you can supply a second parameter for the numerical system to use.
By the way, in your final example it should be ++value if you want it to equal 6.
I have this function (going trough the Eloquent Javascript Tutorial chapter 3):
function absolute(number) {
if (number < 0)
return -number;
else
return number;
}
show(absolute(prompt("Pick a number", "")));
If I run it and enter -3 the output will be 3 as expectet but if I enter just 3 the output will be "3" (with double quotes). I can get around by changing
return number;
to
return Number(number);
but why is that necessary? What am I missing?
prompt() always returns a string, but when you enter a negative number, it is handed to the -number call and implicitly converted to a Number. That doesn't happen if you pass it a positive, and the value received by prompt() is returned directly.
You can, as you discovered, cast it with Number(), or you can use parseInt(number, 10), or you could do -(-number) to flip it negative, then positive again, or more obviously as pointed out in comments, +number. (Don't do --number, which will cast it to a Number then decrement it)
Javascript is not strongly typed.
number comes from the prompt() function, which returns a string.
Since you aren't doing anything to change its type, it remains a string.
-number implicitly converts and returns an actual number.
If you have a string that needs to be converted to a number, please do the following:
var numString = '3';
var num = parseInt(numString);
console.log(num); // 3
JavaScript performs automatic conversion between types. Your incoming "number" is most likely string (you can verify by showing result of typeof(number)).
- does not take "string" as argument, so it will be converted to number first and than negated. You can get the same behavior using unary +: typeof(+ "3") is number when typeof("3") is string.
Same happens for binary - - will convert operands to number. + is more fun as it work with both strings "1"+"2" is "12", but 1+2 is 3.