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);
Related
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.
This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 2 years ago.
I want to format a number (225121894) so its formatted as 225,121,894 I pull all the numbers from a JSON and sort and process.
Here is my code
function getTestStats(jsonData)
{
let totalTest = 0
let totalCases = 0
jsonData.map(covid =>
{
if(covid.tested !== "NA") totalTest += Number(covid.tested)
})
document.getElementById('covidTestStatPG').innerHTML += `${totalTest}`
}
Try using Number.toLocaleString(). Not only does this handle the problem of comma-separation, but it handles any type of locale-standard display settings. Below, I use en-US, but not every country/region formats commas the same, so this allows you to change as needed (i.e., to en-IN for Indian-English, etc.) without coding it up yourself everytime...
var number = 123456789;
console.log(number.toLocaleString('en-US'));
/*
CODE FOR NUMBER FORMAT
*/
function numFormat(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
console.log( numFormat(224405) );
/*
YOUR CODE
*/
var jsonData = [{tested:"225121894"}]; // Dummay JSON Data
function getTestStats(jsonData)
{
let totalTest = 0
let totalCases = 0
jsonData.map(covid =>
{
if(covid.tested !== "NA") totalTest += Number(covid.tested)
})
document.getElementById('covidTestStatPG').innerHTML += `${numFormat(totalTest)}`
}
getTestStats(jsonData)
<div id="covidTestStatPG">🎁</div>
You may want to check out Intl.NumberFormat.
I've used it before as follows (this is typescript but you get the idea):
const locale = "en-US";
static formatNumber(rawNumber?: number) {
return rawNumber ? Intl.NumberFormat(locale).format(rawNumber) : "-";
}
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.
Google Contacts now (Jan 2019) issues a long (19 digit) decimal number id for each contact that you create.
Unfortunately, as discussed in this question the ID cannot be put into a URL to view the contact easily, however if you convert this decimal number to Hex it can be put into the URL.
So the question is, how to convert
c2913347583522826972
to
286E4A310F1EEADC
When I use the Decimal to Hex converter here it gives me
286E4A310F1EEADC if I drop the c (2nd function below is a version of the sites code, but it does use PHP too maybe)
However trying the following functions in Javascript give me mixed results
The first one is from this stack question which is the closest, just 2 digits off
function decimalToHexString(number)
{
number = parseFloat(number);
if (number < 0)
{
number = 0xFFFFFFFF + number + 1;
}
return number.toString(16);
}
console.log(decimalToHexString('2913347583522826972'));
//output 286e4a310f1eea00
function convertDec(inp,outp) {
var pd = '';
var output ;
var input = inp;
for (i=0; i < input.length; i++) {
var e=input[i].charCodeAt(0);var s = "";
output+= e + pd;
}
return output;
}
//return 50574951515255535651535050565054575550
Love to know your thoughts on improving this process
It seems like the limit of digit size. You have to use arrays if you need to convert bigger digits.
You can use hex2dec npm package to convert between hex and dec.
>> converter.decToHex("2913347583522826972", { prefix: false }
//286e4a310f1eeadc
Js example
On python side, you can simply do
dec = 2913347583522826972
// Python implicitly handles prefix
hexa = hex(dec)
print dec == int(hexa, 16)
// True
Python example
For more take a look at the following gist
https://gist.github.com/agirorn/0e740d012b620968225de58859ccef5c
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));
}