Formatting Number in JavaScript [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript adding zeros to the beginning of a string (max length 4 chars)
javascript format number to have 2 digit
How can I format number to 3 digits like..
9 => 009
99 => 099
100 => 100

This is trivial.
var num = 9;
num = ""+num;
while(num.length < 3) num = "0"+num;
You can make this into a function easily yourself.

function pad(number, length)
{
var result = number.toString();
var temp = length - result.length;
while(temp > 0)
{
result = '0' + result;
temp--;
}
return result;
}

Surely you need to convert those numbers in strings, because numbers datatype don't "support" initial zeros.
You can toString() the number, then check his length (NUMLENGTH), if it's less than the total number of digits you need (MAXDIGITS) then prepend MAXDIGITS-NUMLENGTH zeros to the string.

http://jsfiddle.net/K3mwV/
String.prototype.repeat = function( num ) {
return new Array( num + 1 ).join( this );
}
for (i=1;i <= 100;i++) {
e = i+'';
alert('0'.repeat(3 - e.length)+i);
}

function padZeros(zeros, n) {
// convert number to string
n = n.toString();
// cache length
var len = n.length;
// if length less then required number of zeros
if (len < zeros) {
// Great a new Array of (zeros required - length of string + 1)
// Then join those elements with the '0' character and add it to the string
n = (new Array(zeros - len + 1)).join('0') + n;
}
return n;
}

Related

How to Convert text of adjacent numbers to displayed as text of number's thousands comma separated? [duplicate]

This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 3 years ago.
Question:
I have 12345678 as text how to get 12,345,678? And as many more numbers between single quote?
I tried this code, but it's qualified for 123456.length <= 6 :-
if (int.length > 3) {
int = int.substr(0, int.length - 3) + "," + int.substr(int.length - 3, 3);
}
function comma(num) {
var newNum;
var len = num.length;
if (len > 3) {
var comNo = len % 3;
newNum = num
.split("")
.reverse()
.join("")
.match(/.{1,3}/g)
.map(function(current) {
return current
.split("")
.reverse()
.join("");
});
newNum.reverse();
return newNum.join();
} else {
return num;
}
}
int = comma(int);

Javascript - How to sum up all the first and last digit of a number until only two digits are left?

I am fairly new to programming, just knowing the basics in Javascript and Swift. I am trying to write a simple program which creates, from any entered number, a two digit number by summing up the first and last digit until only two digits are finally left.
Here is an example:
num = 1234567:
1+7 = 8
2+6 = 8
3+5 = 8
4 remains
So the first result is: 8884. Now everything is added again:
8+8 = 16
8+4 = 12
The result is 1612. Again everything is summed up:
1+2 = 3
6+1 = 7
The result is 37 - which is also the final result.
I am struggling with two things. First the while loop. I was thinking about casting num.toString() and then do a while loop like this in which I change the string to an int again:
num.toString()
while (num.length > 2) {
num = num.parseInt(num, 10);
...
}
But this doesn't work properly, plus it gets crazy complicated I guess because I would have to switch between string and int each new round, right?
I know how to add all digits together until I get a two digit number (it took me a while to figure this one out) and I am not even sure if this is a good way to do it:
var sum = num
.toString()
.split('')
.map(Number)
.reduce(function (a, b) {
return a + b;
}, 0);
But obviously I cannot use this here and I have no idea how to change the code so that the first and last digit are added together.
Slightly different approach:
function sum(num) {
var numString = num.toString();
var newString = "";
while (numString.length > 1) { // (1)
newString += (parseInt(numString[0]) + parseInt(numString[numString.length - 1])).toString(); // (2)
numString = numString.substring(1, numString.length - 1); // (3)
}
newString += numString; // (4)
if (newString.length > 2) { // (5)
console.log(newString)
return sum(newString);
} else {
return newString;
}
}
console.log(sum(1234567));
Outputs:
8884
1216
73
Brief explanation of what's going on:
(1) Your while loop will process the string until there's either 1 or
0 characters left
(2) Add the sum of your first and last character to
your newString
(3) Remove the first and last characters from your
numString now that they've been saved to the newString. Because
you're overwriting the value in numString and shrinking it, this
will eventually satisfy the while condition of a numString with
less than 2 characters
(4) Add the remaining characters to
newString, which will either be 1 or 0 characters depending on the
length of the original number
(5) if your newString is more than 2
characters, run this method again. Otherwise return your result
Try this buddy. Its just using simple for loop. Its loops upto half of number and add corresponding. The final result according to ur logic should be 73 not 37
function sum(num){
//if num is greater than or equal to 2 end the function and return final value
if(num.length <= 2) return num;
//converting the num to string beacuse first time input will be number
num = String(num);
let result = '';
//creating a loop upto half of length of the num
for(let i = 0;i<num.length/2;i++){
//if the number is not middle one
if(i !== num.length - 1 - i)
{
//adding the sum of corresponding numbers to result
result += parseInt(num[i]) + parseInt(num[num.length - 1 - i]);
}
//if the number is middle number just add it to result
else result += num[i]
}
return sum(result);
}
console.log(sum(1234567))
You could take a nested while loop and check the string length for the outer loop and the left and right indices for the inner loop
function add(n) {
var s = n.toString(),
l, r,
sum;
while (s.length > 2) {
l = 0;
r = s.length - 1;
sum = [];
while (l < r) {
sum.push(+s[l++] + +s[r--]);
}
if (l === r) sum.push(s[l]);
s = sum.join('');
}
return +s;
}
console.log(add(1234567));
The same but with a recursive function.
function add(n) {
var s = n.toString(),
l = 0, r = s.length - 1,
sum = [];
if (s.length <= 2) return n;
while (l < r) sum.push(+s[l++] + +s[r--]);
if (l === r) sum.push(s[l]);
return add(+sum.join(''));
}
console.log(add(1234567));

How to "round" number, by putting zeros after the 2nd digit in javascript

I would like to "round" an integer number, by swapping all the digits after the 2nd digit to zeros. Additionally, if the number has only 1 digit, then don't do anything, and if the number has 2 digits, then swap the 2nd digit to a 0.
Example:
3 => 3
22 => 20
754 => 750
8912 => 8900
Can this be achieved without truncating the number as a string, and then rebuilding the number with zeros?
You don't need to truncate the number as a string, it can be easily achieved via mathematical calculation. Also, changing number to string and then doing any operation will be an added overhead which is not required in this case.
Refer the code below, it's quite straight forward.
Hope this helps.
function changeNumber(num){
if(Math.floor(num/10) == 0){
return num;
} else if(Math.floor(num/1000) == 0){
return Math.floor(num/10)*10;
}
else{
return Math.floor(num/100)*100
}
}
console.log(changeNumber(3));
console.log(changeNumber(22));
console.log(changeNumber(754));
console.log(changeNumber(8923));
That will work with every base-10 number.
All is about a simple math operation: number - [rest of (number / base-10 of number)]
function round(n) {
if(n < 10) return n;
var d = getTenBase(n.toString().length - 1);
return n - (n % (10 * d));
}
function getTenBase(l) {
var d = 1;
for(var i = 2; i < l; i++) {
d *= 10;
}
return d;
}
console.log(round(3));
console.log(round(22));
console.log(round(768));
console.log(round(1657));
you can just find length and first two character after that take zero with valid length and concat both
var str = '8912';
var n = str.length;
if(n == 1)
{
print(str);
} else if(n==2) {
var strFirst = str.substring(0,1);
var str2 = '0';
var res = strFirst.concat(str2);
} else if(n>2) {
var strFirst = str.substring(0,2);
var i;
var strsec ='0';
for (i = 0; i < n-3; i++) {
strsec += 0 ;
}
var res = strFirst.concat(strsec);
}
print(res);

Keep leading zero using javascript [duplicate]

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 3 years ago.
Is there a way to prepend leading zeros to numbers so that it results in a string of fixed length? For example, 5 becomes "05" if I specify 2 places.
NOTE: Potentially outdated. ECMAScript 2017 includes String.prototype.padStart.
You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:
function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}
Or, if you know you'd never be using more than X number of zeros, this might be better. This assumes you'd never want more than 10 digits.
function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}
If you care about negative numbers you'll have to strip the - and read it.
UPDATE: Small one-liner function using the ES2017 String.prototype.padStart method:
const zeroPad = (num, places) => String(num).padStart(places, '0')
console.log(zeroPad(5, 2)); // "05"
console.log(zeroPad(5, 4)); // "0005"
console.log(zeroPad(5, 6)); // "000005"
console.log(zeroPad(1234, 2)); // "1234"
Another ES5 approach:
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
zeroPad(5, 2); // "05"
zeroPad(5, 4); // "0005"
zeroPad(5, 6); // "000005"
zeroPad(1234, 2); // "1234" :)
You could extend the Number object:
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
}
Examples:
(9).pad(); //returns "09"
(7).pad(3); //returns "007"
From https://gist.github.com/1180489
function pad(a, b){
return(1e15 + a + '').slice(-b);
}
With comments:
function pad(
a, // the number to convert
b // number of resulting characters
){
return (
1e15 + a + // combine with large number
"" // convert to string
).slice(-b) // cut leading "1"
}
function zfill(num, len) {return (Array(len).join("0") + num).slice(-len);}
Just for fun (I had some time to kill), a more sophisticated implementation which caches the zero-string:
pad.zeros = new Array(5).join('0');
function pad(num, len) {
var str = String(num),
diff = len - str.length;
if(diff <= 0) return str;
if(diff > pad.zeros.length)
pad.zeros = new Array(diff + 1).join('0');
return pad.zeros.substr(0, diff) + str;
}
If the padding count is large and the function is called often enough, it actually outperforms the other methods...

Way to add leading zeroes to binary string in JavaScript [duplicate]

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 8 years ago.
I've used .toString(2) to convert an integer to a binary, but it returns a binary only as long as it needs to be (i.e. first bit is a 1).
So where:
num = 2;
num.toString(2) // yields 10.
How do I yield the octet 00000010?
It's as simple as
var n = num.toString(2);
n = "00000000".substr(n.length) + n;
You could just use a while loop to add zeroes on the front of the result until it is the correct length.
var num = 2,
binaryStr = num.toString(2);
while(binaryStr.length < 8) {
binaryStr = "0" + binaryStr;
}
Try something like this ...
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
... then use it as ...
pad(num.toString(2), 8);

Categories

Resources