Javascript addition query - javascript

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>

Related

How to perform comma and decimal separation of a number using javascript?

I have a value 2000000 and i want this to be formatted as 2,000,000.00
below is the script i have tried but not able to get the exact output.
function myFunction() {
var num = 2000000;
var c = num.toLocaleString()
var n = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//var number=n.
var number = parseInt(n).toFixed(2);
document.getElementById("demo").innerHTML = n;
document.getElementById("demmo").innerHTML = number;
}
This function gives 2,000,000 and 2.00 but it should be 2,000,000.00
help me to get the required result.
Use toFixed, then add the , and ensure that there are two 0 at the end:
const addTo = (add, length) => str => str.length >= length ? str : addTo(add, length)(str + add);
const chunk = (sym, length) => str => str.length < length ? str : chunk(sym, length)(str.substr(0, str.length - length)) + sym + str.substr(str.length - length);
const [num, fraction] = 2000000..toFixed(2).split(".");
return chunk(",", 3)(num) + "." + addTo("0", 2)(fraction);
You could use the NumberFormat object of the ECMAScript Internationalization API:
let num = 2000000;
let l10nEN = new Intl.NumberFormat("en-US", { minimumFractionDigits: 2 });
console.log(l10nEN.format(num));
Or simply use the toLocaleString() method of the number type:
let num = 2000000;
console.log(num.toLocaleString("en-US", { minimumFractionDigits: 2 }));
function myFunction() {
var num = 2000000.00;
var c = num.toLocaleString();
var substr = c.split('.');
var decimal = substr[1];
var intVal= substr[0];
var n = intVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//var number=n.
var number = n+ decimal;
document.getElementById("demo").innerHTML = n;
document.getElementById("demmo").innerHTML = number;
}
You could use Number.prototype.toLocaleString() and Number.prototype.toFixed() to achieve the required result.
DEMO
let value = 2000000;
value = value.toFixed(2).split('.');
console.log(Number(value[0]).toLocaleString('en') + '.' + value[1]);
value= 2000000.87;
value = value.toFixed(2).split('.');
console.log(Number(value[0]).toLocaleString('en') + '.' + value[1]);
Try this
num.toLocaleString('en', { minimumFractionDigits:2 })

How can I substitute/replace numbers inside a string as a multiplier for the letter inside the string?

For example: m1 = m , m2 = mm, m3i2 = mmmii
I am trying to find a simple way to do this. Any useful methods?
This is not a homework problem. I am just practicing on my Javascript skills.
So easy with regex and repeat:
function f(str) {
return str.replace(/(.)(\d+)/g, (_, s, n) => s.repeat(n));
}
console.log(f('m1')); // 'm'
console.log(f('m2')); // 'mm'
console.log(f('m3i2')); // 'mmmii'
It can behave a bit inconsistent if the string starts with a digit. You may prefer /(\D?)(\d+)/g.
You could split the string and use the result for returning the string
var s = 'm3i2'.split(/(?=[a-z])/),
result = s.reduce(function (r, a) {
var i = +a.slice(1);
while (i--) {
r += a[0];
}
return r;
}, '');
console.log(result);
here in lambda style
"m2s3".split("").reduce((s,c) => isNaN(c) ? s + c : s + s[s.length-1].repeat(c-1));
mmsss
ES5 Example:
var s = 'm3i2j1';
var re = /([a-z])(\d+)/g;
var matches;
var buffer = [];
while (matches = re.exec(s)) {
buffer.push(Array(+matches[2] + 1).join(matches[1]));
}
var output = buffer.join('');
function replaceNumbers(text) {
var match = text.match(/\D\d*/g), ans = '', i, n;
for (i = 0; i < match.length; ++i) {
n = Number(match[i].substr(1));
ans += match[i].substr(0, 1).repeat(n > 0 ? n : 1);
}
return ans;
}
// Here is the solution I came up with.
function letTheNumberDoTheTalking(str) {
var word = '';
var start = 0;
for (var next = 1; next < str.length; next += 2) {
var letter = str[start];
var multipliedLetter = str[start].repeat(str[next]);
word += multipliedLetter;
start = next + 1;
}
return word;
}
letTheNumberDoTheTalking('m1i1s2i1s2i1p2i1')); //==> 'mississippi'

Take random letters out from a string

I want to remove 3 RANDOM letters from a string.
I can use something like substr() or slice() function but it won't let me take the random letters out.
Here is the demo of what I have right now.
http://jsfiddle.net/euuhyfr4/
Any help would be appreciated!
var str = "hello world";
for(var i = 0; i < 3; i++) {
str = removeRandomLetter(str);
}
alert(str);
function removeRandomLetter(str) {
var pos = Math.floor(Math.random()*str.length);
return str.substring(0, pos)+str.substring(pos+1);
}
If you want to replace 3 random charc with other random chars, you can use 3 times this function:
function substitute(str) {
var pos = Math.floor(Math.random()*str.length);
return str.substring(0, pos) + getRandomLetter() + str.substring(pos+1);
}
function getRandomLetter() {
var letters="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var pos = Math.floor(Math.random()*letters.length);
return letters.charAt(pos);
}
You can split the string to an array, splice random items, and join back to a string:
var arr = str.split('');
for(var i=0; i<3; ++i)
arr.splice(Math.floor(Math.random() * arr.length), 1);
str = arr.join('');
var str = "cat123",
amountLetters = 3,
randomString = "";
for(var i=0; i < amountLetters; i++) {
randomString += str.substr(Math.floor(Math.random()*str.length), 1);
}
alert(randomString);
fiddle:
http://jsfiddle.net/euuhyfr4/7/
This answer states that
It is faster to slice the string twice [...] than using a split followed by a join [...]
Therefore, while Oriol's answer works perfectly fine, I believe a faster implementation would be:
function removeRandom(str, amount)
{
for(var i = 0; i < amount; i++)
{
var max = str.length - 1;
var pos = Math.round(Math.random() * max);
str = str.slice(0, pos) + str.slice(pos + 1);
}
return str;
}
See also this fiddle.
you can shuffle characters in your string then remove first 3 characters
var str = 'congratulations';
String.prototype.removeItems = function (num) {
var a = this.split(""),
n = a.length;
for(var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a.join("").substring(num);
}
alert(str.removeItems(3));
You can use split method without any args.
This would return all chars as a array.
Then you can use any randomiser function as described in Generating random whole numbers in JavaScript in a specific range? , then use that position to get the character at that position.
Have a look # my implementation here
var str = "cat123";
var strArray = str.split("");
function getRandomizer(bottom, top) {
return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
alert("Total length " + strArray.length);
var nrand = getRandomizer(1, strArray.length);
alert("Randon number between range 1 - length of string " + nrand);
alert("Character # random position " + strArray[nrand]);
Code # here https://jsfiddle.net/1ryjedq6/

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 make 8 digit number in 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);

Categories

Resources