Convert Ordinal String to its number - javascript

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

Related

how to subtract 1 from a string which is a number

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.

Write a JavaScript function that reverse a number [duplicate]

This question already has answers here:
JavaScript: How to reverse a number?
(19 answers)
Closed 3 years ago.
Result shows "n.split is not a function" unless i include n=n+" " the following code.What does third line mean?
function reverse_a_number(n)
{
n = n + "";
return n.split("").reverse().join("");
}
console.log(reverse_a_number(32243));
There is no split function in Number.prototype. So, n = n + "" is just a simple way to convert a number to a string.
From the spec
If Type(lprim) is String or Type(rprim) is String, then
Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
If one of the operands in an expression with + is a string, the other operand is also coerced to a string and concatenated with it
console.log( 1 + 1 ) // sum
console.log( 1 + "1" ) // concatenation
console.log( true + "string" ) // concatenation
In javascript , there is no Explicit declaration of datatype, by assigning value to the variable , it implicitly takes the datatype like int,string.
In your case,Simple you are applying String function to integer , so you are getting Error.
So first convert integer value into String by using "toString()" function.
Solution:
function reverse_a_number(n) {
//Casting
n=n.toString();
return Number(n.split("").reverse().join(""));
}
console.log(reverse_a_number(32243));
There is no split function for Number. You can do this as an alternate
+String.prototype.split.call(32243,'').reverse().join('')
What the above code does?
I am using split method in String class via context switching for number which returns array.
Then we are reversing the number and joining it.
Then unary plus converts it to number.
As #briosheje mentioned, you can also use the following
+[...''+32243].reverse().join('')
Cast the number to a string and then use split as numerical values don't have the split function. Again cast it to a number while returning
function reverse_a_number(n) {
n=n.toString();
return Number(n.split("").reverse().join(""));
}
console.log(reverse_a_number(32243));
The reason is that split method works only on string values and your passing integer value as argument, that's why it's working only after casting it to string
You can't split a number. By using n = n + "", you're casting it a string and then splitting it. However, you're also returning a string! You'll want to cast it back to an integer before you return it.
Hmm.. I think this could be solved easily.
turn the number to a string, this lets you turn it to an array
Split it to a array
use array's function 'reversed'
join it
turn it to an number or int again.
const number = 3211232;
const numberReversed = parseInt(number.toString().split("").reverse().join(""));
console.log(numberReversed);

String To Number Confusion

Why does parseInt("-1000-500-75-33") return -1000?
Shouldn't it return the sum of those numbers: -1608
How can I get the string "-1000-500-75-33" to return as the sum of those numbers?
parseInt will try to get a number starting from the beginning of the string.
Since - is a valid character to begin a number with, it parses the string until it finds something invalid. The second - is invalid because no integer can contain an - inside it, only digits. So it stops there and considers the number to be "finished".
Now, if you want to process the expression, you can use eval like so:
eval("-1000-500-75-33")
This will return -1608 as expected.
parseInt will not perform any computations, rather it will try to convert a string into an integer. It returns -1000 because the dash afterwards would not be considered a valid number. If you want to sum all these numbers you could split on the dash, map to Number, then reduce:
var numString = "-1000-500-75-33";
numString.split('-').map(e => Number(e)).reduce((a, b) => a - b);
Try to eval! it's safe here
eval("-1000-500-75-33").toString()
console.log(eval("-1000-500-75-33").toString());
And about type casting: After parsing -1000, which is obviously "negative 1000", It will escape casting as soon as it detect a symbol common between numbers & strings. So parseInt is seeing "-1000-500-75-33" as "-1000NotConvertableString", So left the remaining away, returning -1000 as the result of type-casting.
Since they are in a string, ParseInt does not parse the whole string, just finds the first applicable number from the start & returns it. If the start of the string cannot be parsed, it returns NaN
parseInt("-1000NOT_NUMBER") = -1000
parseInt("test-1000`) = NaN
You have to use eval function to do what you want, that evaluates given string as if it were a command entered into the console;
eval("-1000-500-75-33") = -1608

How can I remove all decimals from a JavaScript variable?

How can I remove all decimals from a number? I want to get the number as specified below. I need to remove decimal points only. I am not getting the logic for it.
If number x= 1.1.6;
then I want result as 116
and when x=0.0.6;
then I want result as 6.
Since 1.1.6 is not a valid numerical value in JavaScript, I assume that you're starting with a string. You can get the result as an integer value with:
parseInt(number.replace(/\./g, ''))
If desired, you can then turn that back into a string with no leading zeroes with:
'' + parseInt(number.replace(/\./g, ''))
try this. replace all the . using replace method and convert to integer
document.write(parseInt("1.1.6".replace(/\./g, '')))
document.write('<br>')
document.write(parseInt("0.0.6".replace(/\./g, '')))

Google Spreadsheet Script getValues - Force int instead of string

Is there a way to force .getRange().getValues() to return an int? Although only numbers exist in my range, it is returning them as strings. I would like to avoid using parseInt in every one of my statements or creating a separate array with converted values.
Or is that the only solution, to get the array and then parseInt the entire array in a loop?
you can do this easily using the unary '+' operator as follows:
First get your values from your spreadsheet using getValue() or getValues(). Suppose you get two such values, and store them in A = 1 and B = 2. You can force them to be recognized as numbers by using any math binary operator except for +, which concatenates strings, so A - B = -1, while A + B will return '12'.
You can force the variables to be numbers simply by using the + unary operator with any variable that might be interpreted as a string. For example, +A + +B will return the correct value of 3.
You can use parseInt() or Number()
example
var A='12';var B=5
A+B = 125
parseInt(A)+B = 17
Number(A)+B = 17
That said, getValues() is not supposed to return strings unless values have some space or other non-numeric characters in it... are these values entered manually or come as a result of some function ?
getValues() returns a 2D array of Objects - so these are Strings, Integers or Date objects depending on what these are formatted as in your spreadsheet.
Go back to your spreadsheet and see what the cells that have integer values are formatted as. Format them as integers and you should get back integers.

Categories

Resources