Write a JavaScript function that reverse a number [duplicate] - javascript

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

Related

Convert Ordinal String to its number

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

how to convert 1,800.00 to 1800 in javascript? [duplicate]

This question already has answers here:
How to convert a number with comma as string into float number in Javascript
(2 answers)
Closed 4 years ago.
I am trying to convert 1,100.00 or 1,800.00 to 1100 or 1800 by using Javascript Number() function but it gives NaN.
For Example:
var num = "1,100.00";
console.log(Number(num));
output: NaN
My requirement is If I have a number 1,800.00 it should convert to 1800 in Javascript.
Any help will be appreciated.
Thanks.
You can replace the , char using built-in replace function and then just convert to Number.
let number = "1,100.00";
console.log(Number(number.replace(',','')));
The Number() function converts the object argument to a number that represents the object's value. If the value cannot be converted to a legal number, NaN is returned.
You might have multiple , in the string replace all , from the string before passing to Number():
let numStr = '1,800.00';
let num = Number(numStr.replace(/,/g,''));
console.log(num);
.as-console-wrapper{
top: 0;
}
You can just replace the , with empty '' and then convert the string into number with + operator
let neu = "6,100.00";
document.write(+neu.replace(',',''));
You can try this.
var myValue = '1,800.00';
var myNumber = myValue.replace(/[^0-9.]/g, '');
var result = Math.abs(myNumber);
console.log( Math.floor(myNumber))
Here, in myValue, only number is taken removing other characters except dot.
Next thing is the value is converted to positive number using Math.abs method.
And at last using Math.floor function the fraction part is removed.

What does a + before a string means in javascript

There is a line of code in angular2.
this.id = +this.route.snapshot.params['id'];
What is the "+" means before "this.route.snapshot.params['id']"?
I also see "+" added before a folder name such as "+detail" in angular2-webpack-starter.
Do they have the same meaning?
Using + in Javascript is a quick way to cast a string to a number as long as the string is already in the form of an integer or float.
+'5000' // yields 5000
+'2.5' // yields 2.5
If the string contains any character that is not an integer (or decimal in the case of a float), this method will return NaN.
+'5n' // yields NaN
+'abcd' // yields NaN
enter image description here
In short if you put + operator in front of string which contains Number
then always get number other than that you will get NaN.

Casting a number to a string by adding an array in JavaScript [duplicate]

This question already has answers here:
Why is [1,2] + [3,4] = "1,23,4" in JavaScript?
(14 answers)
Closed 6 years ago.
In JavaScript:
var stringVar = 12345 + []
Will cast the number to a string.
Small demo: https://jsfiddle.net/ce9bjcwo/
Why does this happen?
Due to Array.prototype.toString().
It converts it to a string representation when trying to concatenate, and since 12345 is not a string, it's type-cast to one.
Examples:
[1,2].toString() -> "1,2"
[].toString() -> ""
12345 + "" -> "12345"
It happens because:
There is no way to apply the + operator to an array, so Javascript stringifies the array. Since it's an empty array, it stringifies as ''. Then you have 12345 + ''
And in javascirpt "number" + "string" returns a string, by casting the number to a string and treating + as concatenation operator.
it's due to the fact it is trying to concatenate it to an empty string
You may understand it better if you try something like
var stringVar = ""+123;
the amazing thing is that if you do
stringVar = stringVar - 0 ;
it turns to an integer
then if you evaluate
stringVar == '123'
you get true
but if you evaluate
stringVar === '123'
you get false
so cool

reversing a number in javascript (clarification)

I have a simple question to ask, in which I am slightly embarrassed to ask, but I realize that I won't learn unless I ask.
When looking at reversing a string, I recognize that reversing a string requires you to split up the string, reverse it, and then re-join it. Like so.
var stringReverse = function (n){
return n.split("").reverse().join("");
}
console.log(stringReverse("hello"));
However, I was trying to reverse a number, much of the principles were very similar except for one part. The code below is:
var reverse_a_number = function (n){
n = n + "";
return n.split("").reverse().join("");
}
console.log(reverse_a_number(32243));
My question is why am I needed to bring in the " n = n + " ";" to the code? I was assuming that the same principles would be similar regardless of it being a string, or an integer.
Much thanks in advance, and I apologize that this question is elementary.
why am I needed to bring in the " n = n + " ";" to the code?
Adding + "" will make a cast to String, this way you can use String functions (.split).
The integer have only functionality of a Number. If you want to treat the Number as a String you need to cast it (+ "") or convert it (.toString())
The .reverse() function come from Array object that is created when you use String function .split().
With .join() you come back to String from Array (of characters).
If you want to come back to Number after reverting, you can choose one of these functions.
To put it simply, the docs require it to be a string. You could combine your two methods by doing exactly what you're doing in reverse_a_number (it works for both). Also, don't be embarrassed to ask questions, it's how you learn :)
Number doesn't have reverse and split method directly and you should convert number to string that be able reverse it.
to convert it you can add an empty string after it, like you.
just it.
Javascript sets the type of a variable at runtime.
If she (yes, it's a girl) sees that you only have ciphers, she will consider it's an integer.
Adding + ""; casts it into a string, which is an array of chars.
Your string is stored a lil bit like : ['h', 'e', 'l', 'l', 'o']
an integer is stored as {0011001010101...}
Explanation
You are passing in a number, not a string. When you combine a number with a string ("") it assumes you want to make a string. So you are really converting it to a string. To an array, then back to a string. If you attempt to split a number, the compiler will throw an error. More exactly
TypeError: undefined is not a function (evaluating 'n.split('')')
So what you really are doing is making the number into a String. There are different methods you can use, take a look here.
n += '';(String) ->
.split() (Array) -> .split() (Array) -> .join() (String)
Your function is actually producing and returning a string
Alternative Function
I'm going to critique ;) , you could shorten, and improve this function using the following.
var reverse_a_number = function (n){
return +(n += "").split("").reverse().join("");
}
What does this do?
n = n + '' has a special operator, +=. We can shorten this to on-line by using this inside parenthesis. The + will convert it into a Integer
A number doesn't have the split method. You have to convert it into a string, which does have split.
You can use typeof to find out the type of a variable. The following code snippet demonstrates the types of a number and a string, and shows the value of the split attribute for each one. Note that split is undefined for the number.
var n = 42;
document.write(typeof n, '<br />', n.split, '<br />', '<br />');
var s = ''+n;
document.write(typeof s, '<br />', s.split);
If you want to reverse an integer by treating it as an integer, without using string operations, you can do the following.
function reverseInteger(n) {
var result = 0;
while (n != 0) {
var digit = n%10;
result = 10*result + digit;
n = (n-digit)/10;
}
return result;
}
var n = 3141590123456;
document.write(n, '<br />');
document.write(reverseInteger(n));
Note that the last digit of n is n%10. If we subtract the last digit and divide n by ten, the effect is to shift n one digit to the right. We keep doing this and build up result in reverse by multiplying it by ten on each iteration and adding the digit that we just removed from n.

Categories

Resources