I want to reverse a number t following the tutorial.First I have passed a number as a parameter. I have converted the number to string with to String function. Then I used split("").reverse().join("") to reverse the number.
My code is as follows:
<script type="text/javascript">
function reverse_the_string(num) {
num = String(num);
// str = num.toString;
num.split("").reverse().join("");
return;
}
console.log(reverse_the_string(56789));
</script>
However I get an error undefined? Can anyone explain what is the wrong?
You do not return the result. Use
return num.split("").reverse().join("");
If you use just return, then undefined is returned.
function reverse_the_string(num) {
return String(num).split("").reverse().join("");
}
document.write(reverse_the_string(56789));
Caveat: Reversing works only with small numbers!
Try this (Recursive Method)
function reverseNum(num) {
if(num == 0)return 0;
let x = Math.pow(10, (num + '').length - 1);
return (num % 10) * x + reverseNum(Math.floor(num / 10));
}
console.log(reverseNum(432));
The solution of casting the number into a string and reversing the string is a good solution, BUT it doesn't cover all the cases. There are 2 cases that need to be addressed:
Reversing a negative number it doesn't retain the sign.
Reversing a number that ends with zero(s), after reversing you will have leading zeros, e.g. 12300 the reverse will be "00321" when it should be "321".
Using Regular function
var reversed = parseFloat(num.toString().split("").reverse().join()) * Math.sign(num);
Using Arrow Function
var reversed = num => parseFloat(num.toString().split('').reverse().join('')) * Math.sign(num);
Convert the number variable to a string:
var n = 4557
n = n.toString();
then execute the below code.
//**Reverse the Number In javascript**
var result = "";
function reverseNumber(n){
// reverse the number via loop
for(var i=x.length-1; i>=0; i--){
result+=n[i];
}
return Number(result)
}
var x = prompt("Enter a number : ");
console.log(reverseNumber(x))
In order to reverse number/ string you can refer this method:
(without using slice() and substring() methods)
function reverse(str) {
var rev = "";
number = parseInt(str);
for (; number > 0;) {
rev += number % 10;
number = Math.floor(number / 10)
}
return rev;
}
Related
this is a function just increment one number into array
but the problem i interface when i put alot of numbers into array (more than 16 digits)
when i use parseInt() just returned 16 correct numbers and more than that be zero
6145390195186705000
and expected
6145390195186705543
the function
var plusOne = function(digits) {
var numbersInString = digits.join('');
var theNumbers = parseInt(numbersInString);
var theNumbersPlusOne = theNumbers + 1;
var result = String(theNumbersPlusOne).split("").map((theNumbersPlusOne) => {
return Number(theNumbersPlusOne);
});
return result;
};
console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]));
Just expanding on my above comment with another solution...
You've exceeded the maximum safe integer value. (Number.MAX_SAFE_INTEGER, which equals 9007199254740991). Numbers larger than this are not supported with standard integer types in javascript, or rather there's not enough precision to represent them. Anything larger than this is represented in scientific notation and the extra digits are truncated and represented only as zeroes.
With that said, you don't even need to convert the array to a string to an integer just to increment it. You can just increment the individual digits in the array, starting at the end and working your way forwards to "carry the 1" so to speak.
var plusOne = function(digits) {
for(let i = digits.length - 1; i > -1; i--)
{
if(digits[i] == 9)
{
digits[i] = 0;
if(i == 0)
digits = [1].concat(digits);
}
else
{
digits[i]++;
break;
}
}
return digits;
};
console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]));
You can use BigInt to handle this problem.
var plusOne = function(digits) {
var numbersInString = digits.join('');
var theNumbers = BigInt(numbersInString);
var theNumbersPlusOne = theNumbers + BigInt(1);
var result = theNumbersPlusOne.toString().split("").map((theNumbersPlusOne) => {
return Number(theNumbersPlusOne);
});
return result;
};
console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]));
i'm having a serious issue here. I have a function that pads a user's input with zeros. For example if i enter 88 it will normalize it to:
00000088. My function is this:
export default length => (value) => {
const noLeadingZeros = value.toString().replace(/(0+)/, '');
if (noLeadingZeros.length === 0) {
return value;
}
return padLeft(noLeadingZeros, length);
};
with padleft is:
export default (num, len) => (
len > num.toString().length ? '0'.repeat(len - num.toString().length) + num
: num
);
My problem is that if i entered something like this:
80112345 it convert it to 08112345. Any ideas?
Using slice:
let str = '00000000' + 88;
let resp = str.slice(-8, str.length)
console.log(resp) // 00000088
In your replace, you're replacing all the zeros in the number not just those on the left side, and even if there are zeros on the left side, why remove them if you're just going to add them back. You could use a for loop that pads the string with a zero n times (where n is the number of digits that the string needs to have length 8), or (thanks to a comment by #AndrewBone), you can use the .repeat() function that does this for you:
function padLeft(value, len) {
return '0'.repeat(String(value).length < len ? len - String(value).length : 0) + value;
}
console.log(padLeft("", 8));
console.log(padLeft("88", 8));
console.log(padLeft("00088", 8));
console.log(padLeft("12312388", 8));
console.log(padLeft("00000000", 8));
this looks wrong :
const noLeadingZeros = value.toString().replace(/(0+)/, '');
you are deleting every zeros out of your number... even those inside !
You can use this regex instead, instead of for /(0+)/ in your code :
/\b(0+)/
explanation : the \b ensures the zeros are at the beginning of a word
or this
/^(0+)/
explanation : the ^ ensure this is the beginning of the string
Just use a RegEx to assert that the number is a valid number.
/0+/
Then get the number of digits in the number:
('' + num).length;
Then put the whole thing together
var paddedNum ='';
for (var i=0;i<8-len;i++) {
paddedNum += "0";
}
paddedNum += num;
I'm converting a CSV file to a local 2D array. I wanted to know if there is a better way to convert strings to floats/int rather then using regex followed by a parseFloat() / parseInt.
Ideas / Suggestions?
// numex() - checkes to see if the string (str) is a number
// returns number.valid (true||false) and number.value = (float||int||string)
numex = function(str){
number = {};
number.valid = false;
number.value = str;
// if we see a number then convert it to a floating point or integer
if((number.value.search(/[^0-9^\.^\$^\%^\-^\"^,^ ]+/) < 0) && str.length > 0) {
number.valid = true;
number.value = str.replace(/[^\-^0-9^\.]+/g, ''); // TODO add % coversion code for example if we see a 10% covert it to .1
if(number.value.search(/[\.]/) >= 0) {
number.value = parseFloat(number.value); // replace floating point
} else {
number.value = parseInt(number.value); // replace integers
}
}
return number; // number.valid = true or false;
}
var num = numex("1.101");
alert(num.value);
I don't think you need to use regexp at all. Try this:
var num = {};
num.value = new Number(str);
num.valid = !isNaN(num.value);
Number constructor is more strict than parseInt and parseFloat in that it does not accept strings like 10aaa or 1.2bbb so there is no need to perform a regexp check.
I simplified the code greatly and used something similar to what LeZuse did.
isNaN(value) || value == ""
https://github.com/designpro/jCSV
i want int from string in javascript how i can get them from
test1 , stsfdf233, fdfk323,
are anyone show me the method to get the integer from this string.
it is a rule that int is always in the back of the string.
how i can get the int who was at last in my string
var s = 'abc123';
var number = s.match(/\d+$/);
number = parseInt(number, 10);
The first step is a simple regular expression - \d+$ will match the digits near the end.
On the next step, we use parseInt on the string we've matched before, to get a proper number.
You can use a regex to extract the numbers in the string via String#match, and convert each of them to a number via parseInt:
var str, matches, index, num;
str = "test123and456";
matches = str.match(/\d+/g);
for (index = 0; index < matches.length; ++index) {
num = parseInt(matches[index], 10);
display("Digit series #" + index + " converts to " + num);
}
Live Example
If the numbers really occur only at the ends of the strings or you just want to convert the first set of digits you find, you can simplify a bit:
var str, matches, num;
str = "test123";
matches = str.match(/\d+/);
if (matches) {
num = parseInt(matches[0], 10);
display("Found match, converts to: " + num);
}
else {
display("No digits found");
}
Live example
If you want to ignore digits that aren't at the end, add $ to the end of the regex:
matches = str.match(/\d+$/);
Live example
var str = "stsfdf233";
var num = parseInt(str.replace(/\D/g, ''), 10);
var match = "stsfdf233".match(/\d+$/);
var result = 0; // default value
if(match != null) {
result = parseInt(match[0], 10);
}
Yet another alternative, this time without any replace or Regular Expression, just one simple loop:
function ExtractInteger(sValue)
{
var sDigits = "";
for (var i = sValue.length - 1; i >= 0; i--)
{
var c = sValue.charAt(i);
if (c < "0" || c > "9")
break;
sDigits = c + sDigits;
}
return (sDigits.length > 0) ? parseInt(sDigits, 10) : NaN;
}
Usage example:
var s = "stsfdf233";
var n = ExtractInteger(s);
alert(n);
This might help you
var str = 'abc123';
var number = str.match(/\d/g).join("");
Use my extension to String class :
String.prototype.toInt=function(){
return parseInt(this.replace(/\D/g, ''),10);
}
Then :
"ddfdsf121iu".toInt();
Will return an integer : 121
First positive or negative number:
"foo-22bar11".match(/-?\d+/); // -22
javascript:alert('stsfdf233'.match(/\d+$/)[0])
Global.parseInt with radix is overkill here, regexp extracted decimal digits already and rigth trimmed string
I am trying to increment a number by a given value each second and retain the formatting using JavaScript or JQuery
I am struggling to do it.
Say I have a number like so:
1412015
the number which this can be incremented by each second is variable it could be anything beween 0.1 and 2.
Is it possible, if the value which it has to be incremented by each second is 0.54 to incremenet the number and have the following output:
1,412,016
1,412,017
1,412,018
Thanks
Eef
I'm not quite sure I understand your incrementation case and what you want to show.
However, I decided to chime in on a solution to format a number.
I've got two versions of a number format routine, one which parses an array, and one which formats with a regular expression. I'll admit they aren't the easiest to read, but I had fun coming up with the approach.
I've tried to describe the lines with comments in case you're curious
Array parsing version:
function formatNum(num) {
//Convert a formatted number to a normal number and split off any
//decimal places if they exist
var parts = String( num ).replace(/[^\d.]-/g,'').split('.');
//turn the string into a character array and reverse
var arr = parts[0].split('').reverse();
//initialize the return value
var str = '';
//As long as the array still has data to process (arr.length is
//anything but 0)
//Use a for loop so that it keeps count of the characters for me
for( var i = 0; arr.length; i++ ) {
//every 4th character that isn't a minus sign add a comma before
//we add the character
if( i && i%3 == 0 && arr[0] != '-' ) {
str = ',' + str ;
}
//add the character to the result
str = arr.shift() + str ;
}
//return the final result appending the previously split decimal place
//if necessary
return str + ( parts[1] ? '.'+parts[1] : '' );
}
Regular Expression version:
function formatNum(num) {
//Turn a formatted number into a normal number and separate the
//decimal places
var parts = String( num ).replace(/[^\d.]-/g,'').split('.');
//reverse the string
var str = parts[0].split('').reverse().join('');
//initialize the return value
var retVal = '';
//This gets complicated. As long as the previous result of the regular
//expression replace is NOT the same as the current replacement,
//keep replacing and adding commas.
while( retVal != (str = str.replace(/(\d{3})(\d{1,3})/,'$1,$2')) ) {
retVal = str;
}
//If there were decimal points return them back with the reversed string
if( parts[1] ) {
return retVal.split('').reverse().join('') + '.' + parts[1];
}
//return the reversed string
return retVal.split('').reverse().join('');
}
Assuming you want to output a formatted number every second incremented by 0.54 you could use an interval to do your incrementation and outputting.
Super Short Firefox with Firebug only example:
var num = 1412015;
setInterval(function(){
//Your 0.54 value... why? I don't know... but I'll run with it.
num += 0.54;
console.log( formatNum( num ) );
},1000);
You can see it all in action here: http://jsbin.com/opoze
To increment a value on every second use this structure:
var number = 0; // put your initial value here
function incrementNumber () {
number += 1; // you can increment by anything you like here
}
// this will run incrementNumber() every second (interval is in ms)
setInterval(incrementNumber, 1000);
This will format numbers for you:
function formatNumber(num) {
num = String(num);
if (num.length <= 3) {
return num;
} else {
var last3nums = num.substring(num.length - 3, num.length);
var remindingPart = num.substring(0, num.length - 3);
return formatNumber(remindingPart) + ',' + last3nums;
}
}
function rounded_inc(x, n) {
return x + Math.ceil(n);
}
var x = 1412015;
x = rounded_inc(x, 0.54);