Javascript: For loop, progressive numbers with same digits [duplicate] - javascript

This question already has answers here:
Is there a JavaScript function that can pad a string to get to a determined length?
(43 answers)
Closed 6 years ago.
Sorry for the misunderstanding title, I don't know how could explain better.
That's my problem: I have this loop
for(i=1; i<1000; i++){
"MyName_"+i;
}
This will give the following
MyName_1
MyName_2
...
MyName_10
...
MyName_100
How can I do, in a easy way, to have the same number of digits anytime?
This means
MyName_001
...
MyName_010
...
MyName_100
obviously without doing stuff like
if(i<10)
...
if((i>10)&&(i<100))
because the input number is a input so it may be 1000, 10000 or 10000000 and I don't want to write tons of "if()"...
Thank you

Use JavaScript String#slice method
var input = 100; //input any number
var len = input.toString().length;
for (i = 1; i < input; i++) {
console.log("MyName_" + ('000000000000000' + i).slice(-len));
}

Related

Javascript - Online Coding assessment to mask credit cards numbers with # [duplicate]

This question already has answers here:
Masking credit card number
(5 answers)
Closed 12 months ago.
I got the below coding assessment question in Javascript. I tried my best to solve but there are few edge cases I missed. I need help to identify those missing cases
Usually when you buy something, you're asked whether your credit card number, phone number or answer to your most secret question is still correct.
However, since someone could look over your shoulder, you don't want that shown on your screen. Instead, we mask it.
This is what I tried so far
function maskify (cc) {
if (cc.length < 6) {
let reversed = reverse(cc);
let newString = '';
for (let i = 0; i < reversed.length; i++) {
if (i < 4) {
newString += reversed[i];
} else {
newString += '#';
}
}
return reverse(newString);
Output
This is my solution:
function maskify (cc) {
// If less than 6 characters return full number
if (cc.length < 6)
return cc;
// Take out first character
let firstChar = cc.charAt(0);
cc = cc.slice(1);
// Replace characters except last 4
cc = cc.replace(/\d(?=.{4,}$)/g, '#');
// Add first character back
cc = firstChar + cc;
return cc;
}
// Run every example number
const tests = ["4556364607935616", "4556-3646-0793-5616",
"64607935616", "ABCD-EFGH-IJKLM-NOPQ",
"A1234567BCDEFG89HI", "12345", "", "Skippy"];
tests.forEach((number) => console.log(`Testing: ${number} - Output: ${maskify(number)}`));
I ran it with all the numbers of your example and it gets the correct output.

Average calculator finding strange and incorrect numbers [duplicate]

This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Closed 3 years ago.
I am trying to make an average calculator. This is my code for it:
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = prompt("Enter a piece of data (must be a number)");
data.push(newdata);
var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total += data[i];
i++;
}
}
var average = total / data.length;
document.write(average);
It seems to take input well, however something goes wrong when it comes to calculation. It says that the average of 6 and 6 is 33, 2 and 2 is 11, and 12 and 6 is 306. These are obviously wrong. Thank you in advance for your help.
You need to take a number, not a string value from the prompt.
The easiest was is to take an unary plus + for converting a number as string to a number
data.push(+newdata);
// ^
Your first example shows, with '6' plus '6', you get '66', instead of 12. The later divsion converts the value to a number, but you get a wrong result with it.
It is taking the input as string. Convert the input to floats before putting them in the array. I think its performing string additions like 6+6=66 and then 66/2 = 33. Similar is the case of 2 and 2.

Javascript putting comma in text [duplicate]

This question already has answers here:
How to format numbers as currency strings
(67 answers)
Closed 5 years ago.
I'm having problems with my (javascript) API. When I use the coinmarketcap API (https://api.coinmarketcap.com/v1/ticker). As for "max_supply" for bitcoin, it gives me "16865112.0" in text. This is a problem. I want to automatically put comma's in the number like 16,865,112.0 normally I use toLocaleString() but it is marked as text and it doesnt work.
$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
for (var i = 0; i < data.length - 1; i++) {
if (data[i].id == "bitcoin") {
$("#total_supply").html(data[i].total_supply.toLocaleString());
}
}
});
Any suggestions?
You are calling Number.toLocaleString on String. You need to convert it to Number first by calling parseInt or Number() constructor (you can change your current locale too).
$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
for (var i = 0; i < data.length - 1; i++) {
if (data[i].id == "bitcoin") {
$("#total_supply").html(Number(data[i].total_supply).toLocaleString('en-US'));
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="total_supply"></div>
You can still do it, just first convert string to number.
var value = "16865112.0";
value = +value; // convert to number
var fV = Number(value).toLocaleString();
console.log(fV);

Javascript wrong math [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 6 years ago.
I'm not sure what's wrong.
There are two variables, cena and uhrada. cena = 10 and uhrada = 279.8. I want to add them but I am getting 279.810 instead of 289.8.
Thanks for any help!
function priplatok(vstup1, vstup2) {
var chid = vstup1;
var cena = vstup2;
var uhrada = document.getElementById('uhr').value;
if (document.getElementById(chid).checked) {
var pridatu = uhrada + cena;
alert(pridatu);
}
}
The reason is that the values you take from the HTML input elements are always strings, even when they look like numbers. You have to first convert them, for instance with parseInt(...) or parseFloat():
var pridatu = parseFloat(uhrada) + parseFloat(cena);
A shorter way is to force conversion with a +:
var pridatu = +uhrada + +cena;
Although this is concise, you should probably first check if the input really is numeric. I refer to a popular question "Validate decimal numbers in JavaScript - IsNumeric()".
You get a string from document.getElementById('uhr').value.
If you want to do math, you need to cast the value either with parseInt(string, 10) or with parseFloat(string) to a number, implicit with a unary plus.
Your code:
function priplatok(vstup1, vstup2) {
var chid = vstup1;
var cena = vstup2;
var uhrada = +document.getElementById('uhr').value; // use implicit cast to number
if (document.getElementById(chid).checked) {
var pridatu = uhrada + cena;
alert(pridatu);
}
}
Thats because the values are strings and not numbers.
You have to make them numbers first and then calculate:
var pridatu = parseInt(uhrada) + parseInt(cena);

Javascript sum of values in table [duplicate]

This question already has answers here:
How to format a float in javascript?
(14 answers)
Formatting a number with exactly two decimals in JavaScript
(32 answers)
Closed 9 years ago.
I've succesfully used this code to calculate sums in a table:
var $overall = 0;
$("tr.sum").each(function()
{
var $qnt = $(this).find("td").eq(0);
var $price = $(this).find("td").eq(1);
console.log($qnt+" | "+$price);
var sum = parseFloat($price.text()) * parseFloat($qnt.text());
$(this).find("td").eq(2).text(sum);
$overall+= sum;
});
$("#total").text($overall); });
I changed one line to avoid rounding errors:
var sum = parseFloat((parseFloat($price.text().replace(',', '.')) * parseFloat($qnt.text().replace(',', '.'))).toFixed(2));
It works fine. But I can't solve the problem to round the total sum to two decimal places.
$("#total").text($overall);
I tried toFixed(2). But this results in a string and not a number.
Any help would be appreciated!
Thanks, Mike
after doing all calculation make it like this
$overall.toFixed(2);

Categories

Resources