How to make 8 digit number in javascript? - javascript

I am trying to make an auto-generator of numbers. but I'm having a problem on how to forced the number to 8 digit.
for(i=1;i<=100;i++) {
var i = x++;
var test = i.toFixed(8); // I used this but this is only for decimals
jQuery('.generated_table').append(test+'<br />');;
}
Please help.

Use toPrecision:
(10000000).toPrecision(8); //=> '10000000'
(100).toPrecision(8); //=> '100.00000'
If you meant preceding a number with leading zero's:
var i = (100).toPrecision(8).split('.').reverse().join(''); //=> '00000100'
You can also make a Number.prototype function of that:
Number.prototype.leadingZeros = function(n) {
return this.toPrecision(n).split('.').reverse().join('');
};
(100).leadinZeros(8); //=> '00000100'
Just to be complete: a more precise way to print any (number of) leading character(s) to any number may be:
Number.prototype.toWidth = function(n,chr) {
chr = chr || ' ';
var len = String(parseFloat(this)).length;
function multiply(str,nn){
var s = str;
while (--nn>0){
str+=s;
}
return str;
}
n = n<len ? 0 : Math.abs(len-n);
return (n>1 && n ? multiply(chr,n) : n<1 ? '' : chr)+this;
};
(100).toWidth(8,'0'); //=> 00000100

Whooo!!! i got anser :: Try it
for(i=1;i<=100;i++) {
//var i = x++;
var test = i.toPrecision(8).replace("\.","");
jQuery('.generated_table').append(test+'<br />');;
}

Check out this SO question for some links to various printf-style functions for Javascript: Javascript printf/string.format

var randNum = "";
var MAX_LENGTH = 8;
while(randNum.toString().length < MAX_LENGTH){
var temp = Math.floor(Math.random() * 10);
randNum += temp.toString();
}
alert(randNum);

Related

How to increment a string in JavaScript containing leading zeros?

I have string like:
MPG_0023
I want to find something like
MPG_0023 + 1
and I should get
MPG_0024
How to do that in JavaScript? It should take care that if there are no leading zeros, or one leading zero should still work like MPG23 should give MPG24 or MPG023 should give MPG024.
There should be no assumption that there is underscore or leading zeros, the only thing is that first part be any string or even no string and the number part may or may not have leading zeros and it is any kind of number so it should work for 0023 ( return 0024) or for gp031 ( return gp032) etc.
Here's a quick way without using regex.. as long as there's always a single underscore preceding the number and as long as the number is 4 digits, this will work.
var n = 'MPG_0023';
var a = n.split('_');
var r = a[0]+'_'+(("0000"+(++a[1])).substr(-4));
console.log(r);
Or if you do wanna do regex, the underscore won't matter.
var n = "MPG_0099";
var r = n.replace(/(\d+)/, (match)=>("0".repeat(4)+(++match)).substr(-4));
console.log(r);
You can use the regular expressions to make the changes as shown in the following code
var text = "MPG_0023";
var getPart = text.replace ( /[^\d.]/g, '' ); // returns 0023
var num = parseInt(getPart); // returns 23
var newVal = num+1; // returns 24
var reg = new RegExp(num); // create dynamic regexp
var newstring = text.replace ( reg, newVal ); // returns MPG_0024
console.log(num);
console.log(newVal);
console.log(reg);
console.log(newstring);
Using regex along with the function padStart
function add(str, n) {
return str.replace(/(\d+)/, function(match) {
var length = match.length;
var newValue = Number(match) + n;
return newValue.toString(10).padStart(length, "0");
});
}
console.log(add("MPG_023", 101));
console.log(add("MPG_0023", 101));
console.log(add("MPG_0000023", 10001));
console.log(add("MPG_0100023", 10001));
Using regular expression you can do it like this.
var text1 = 'MPG_0023';
var text2 = 'MPG_23';
var regex = /(.*_[0]*)(\d*)/;
var match1 = regex.exec(text1);
var match2 = regex.exec(text2);
var newText1 = match1[1] + (Number(match1[2]) + 1);
var newText2 = match2[1] + (Number(match2[2]) + 1);
console.log(newText1);
console.log(newText2);
Increment and pad the same value (comments inline)
var prefix = "MPG_"
var padDigit = 4; //number of total characters after prefix
var value = "MPG_0023";
console.log("currentValue ", value);
//method for padding
var fnPad = (str, padDigit) => (Array(padDigit + 1).join("0") + str).slice(-padDigit);
//method to get next value
var fnGetNextCounterValue = (value) => {
var num = value.substring(prefix.length); //extract num value
++num; //increment value
return prefix + fnPad(num, padDigit); //prepend prefix after padding
};
console.log( "Next", value = fnGetNextCounterValue(value) );
console.log( "Next", value = fnGetNextCounterValue(value) );
console.log( "Next", value = fnGetNextCounterValue(value) );
One way would e to split the string on the "_" character, increment the number and then add the zeros back to the number.
var testString = "MGP_0023";
var ary = testString.split("_");
var newNumber = Number(ary[1]) + 1;
var result = ary[0] + pad(newNumber);
// helper function to add zeros in front of the number
function pad(number) {
var str = number.toString();
while (str.length < 4) {
str = '0' + str;
}
return str;
}
You could cast to number, increment the value and cast back. Then check if you need leading zeros by looking at the length of the string.
Snippet below:
let str = "MPG_0023",
num = Number(str.substr(4)) + 1,
newStr = String(num);
function addLeading0(str) {
return str.length === 2 ? '00' + str : (str.length === 3 ? '0' + str : str);
}
console.log("MPG_" + addLeading0(newStr));

Javascript addition query

Don't feel foolishness in my question. Below is my scenario. Please advice
var num = 02;
var add = num + 1 ;
Getting result is 3, but I need it as 03. Is it possible.
You'll need to write a padding function:
function strpad(string, length, padChar)
{
var o = string.toString();
if(!padChar)
{
padChar = '0';
}
while (o.length < length)
{
o = padChar + o;
}
return o;
};
And then call it using:
var num = 3;
var add = strpad((3 + 1), 2); // will return '04' as a string.
you can do it like this
<script>
var num=2;
var add= parseInt(num + 2);
if(parseInt(add) <10)
{
add= '0'+add; // if single digit no. then concat 0 before the no.
}
</script>

How to convert a very large hex number to decimal in javascript

I am trying without much success to convert a very large hex number to decimal.
My problem is that using deciaml = parseInt(hex, 16)
gives me errors in the number when I try to convert a hex number above 14 digits.
I have no problem with this in Java, but Javascript does not seem to be accurate above 14 digits of hex.
I have tried "BigNumber" but tis gives me the same erroneous result.
I have trawled the web to the best of my ability and found web sites that will do the conversion but cannot figure out how to do the conversion longhand.
I have tried getting each character in turn and multiplying it by its factor i.e. 123456789abcdef
15 * Math.pow(16, 0) + 14 * Math.pow(16, 1).... etc but I think (being a noob) that my subroutines may not hev been all they should be because I got a completely (and I mean really different!) answer.
If it helps you guys I can post what I have written so far for you to look at but I am hoping someone has simple answer for me.
<script>
function Hex2decimal(hex){
var stringLength = hex.length;
var characterPosition = stringLength;
var character;
var hexChars = new Array();
hexChars[0] = "0";
hexChars[1] = "1";
hexChars[2] = "2";
hexChars[3] = "3";
hexChars[4] = "4";
hexChars[5] = "5";
hexChars[6] = "6";
hexChars[7] = "7";
hexChars[8] = "8";
hexChars[9] = "9";
hexChars[10] = "a";
hexChars[11] = "b";
hexChars[12] = "c";
hexChars[13] = "d";
hexChars[14] = "e";
hexChars[15] = "f";
var index = 0;
var hexChar;
var result;
// document.writeln(hex);
while (characterPosition >= 0)
{
// document.writeln(characterPosition);
character = hex.charAt(characterPosition);
while (index < hexChars.length)
{
// document.writeln(index);
document.writeln("String Character = " + character);
hexChar = hexChars[index];
document.writeln("Hex Character = " + hexChar);
if (hexChar == character)
{
result = hexChar;
document.writeln(result);
}
index++
}
// document.write(character);
characterPosition--;
}
return result;
}
</script>
Thank you.
Paul
The New 'n' Easy Way
var hex = "7FDDDDDDDDDDDDDDDDDDDDDD";
if (hex.length % 2) { hex = '0' + hex; }
var bn = BigInt('0x' + hex);
var d = bn.toString(10);
BigInts are now available in most browsers (except IE).
Earlier in this answer:
BigInts are now available in both node.js and Chrome. Firefox shouldn't be far behind.
If you need to deal with negative numbers, that requires a bit of work:
How to handle Signed JS BigInts
Essentially:
function hexToBn(hex) {
if (hex.length % 2) {
hex = '0' + hex;
}
var highbyte = parseInt(hex.slice(0, 2), 16)
var bn = BigInt('0x' + hex);
if (0x80 & highbyte) {
// You'd think `bn = ~bn;` would work... but it doesn't
// manually perform two's compliment (flip bits, add one)
// (because JS binary operators are incorrect for negatives)
bn = BigInt('0b' + bn.toString(2).split('').map(function (i) {
return '0' === i ? 1 : 0
}).join('')) + BigInt(1);
bn = -bn;
}
return bn;
}
Ok, let's try this:
function h2d(s) {
function add(x, y) {
var c = 0, r = [];
var x = x.split('').map(Number);
var y = y.split('').map(Number);
while(x.length || y.length) {
var s = (x.pop() || 0) + (y.pop() || 0) + c;
r.unshift(s < 10 ? s : s - 10);
c = s < 10 ? 0 : 1;
}
if(c) r.unshift(c);
return r.join('');
}
var dec = '0';
s.split('').forEach(function(chr) {
var n = parseInt(chr, 16);
for(var t = 8; t; t >>= 1) {
dec = add(dec, dec);
if(n & t) dec = add(dec, '1');
}
});
return dec;
}
Test:
t = 'dfae267ab6e87c62b10b476e0d70b06f8378802d21f34e7'
console.log(h2d(t))
prints
342789023478234789127089427304981273408912349586345899239
which is correct (feel free to verify).
Notice that "0x" + "ff" will be considered as 255, so convert your hex value to a string and add "0x" ahead.
function Hex2decimal(hex)
{
return ("0x" + hex) / 1;
}
If you are using the '0x' notation for your Hex String, don't forget to add s = s.slice(2) to remove the '0x' prefix.
Keep in mind that JavaScript only has a single numeric type (double), and does not provide any separate integer types. So it may not be possible for it to store exact representations of your numbers.
In order to get exact results you need to use a library for arbitrary-precision integers, such as BigInt.js. For example, the code:
var x = str2bigInt("5061756c205768697465",16,1,1);
var s = bigInt2str(x, 10);
$('#output').text(s);
Correctly converts 0x5061756c205768697465 to the expected result of 379587113978081151906917.
Here is a jsfiddle if you would like to experiment with the code listed above.
The BigInt constructor can take a hex string as argument:
/** #param hex = "a83b01cd..." */
function Hex2decimal(hex) {
return BigInt("0x" + hex).toString(10);
}
Usage:
Hex2decimal("100");
Output:
256
A rip-off from the other answer, but without the meaningless 0 padding =P

Javascript multiple digit index

I have searched around the net and the solution must be so simple no one has asked?
I just wanted to use an index like + i + to return 001, 002, 003, etc
How about
('000' + i).substr(-3);
So something like this?
function number_pad(num,len) {
num = ""+num;
while(num.length < len) num = "0"+num;
return num;
}
// Usage: number_pad(i,3);
Alternatively, extend the native object:
Number.prototype.pad(len) {
var num = ""+this;
while(num.length < len) num = "0"+num;
return num;
}
// Usage: i.pad(3);
For future reference, this is called zerofill or zero-padding.
function paddedNumber(n) {
// A string containing the fully padded zero value.
var zeroes = "000";
// The number as a string.
var numstr = "" + n;
var nDigits = numstr.length;
// Keep any sign at the front.
var sign = "";
if (/^[\+\-]/.test(numstr)) {
sign = numstr.charAt(0);
numstr = numstr.substring(1);
}
// Concatenates the number with just enough zeroes.
// No padding if itoa is already longer than the pad.
return sign + zeroes.substring(nDigits) + numstr;
}

how to parse string to int in javascript

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

Categories

Resources