Format Whole Numbers JavaScript with Commas [duplicate] - javascript

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) : "-";
}

Related

Why my function returns int without sum of 1, or it sums random number [duplicate]

This question already has answers here:
Large numbers erroneously rounded in JavaScript
(6 answers)
Closed 3 months ago.
I'm trying to convert Steam ID 32bit to Steam ID 64bit.
My javascript function is not working right but same function in python works fine. Python function is copied from How can I get a steamid 64 from a steamID in python
function steamidTo64(steamid) {
let steam64id = 76561197960265728; // Valve's magic constant
let id_split = steamid.split(":");
steam64id += parseInt(id_split[2]) * 2;
if (id_split[1] == "1") {
steam64id += 1;
}
return steam64id;
}
Using input of STEAM_1:1:191000236 function should return 76561198342266201, but instead it returns 76561198342266200
Using input of STEAM_1:1:3645504 function should return 76561197967556737, but it returns 76561197967556740
Using input of STEAM_0:0:570629725 function should return 76561199101525178, but it returns 76561199101525180
You will need to use BigInt since 76561197960265728 is greater than 9007199254740992 (1 digit longer), and so arithmetic operations on this number are inaccurate and can lead to incorrect results.
function steamidTo64(steamid) {
let steam64id = 76561197960265728n;
const id_split = steamid.split(":");
steam64id += BigInt(id_split[2]) * 2n;
if (id_split[1] === "1") steam64id += 1n;
return steam64id;
}
// Result is BigInt
console.log(steamidTo64("STEAM_1:1:191000236").toString());

how to truncate output values in Nerdamer

I am using nerdamer.solve to solve roots but the roots are long and not truncated. I wanted to get truncated values upto 4 decimal places. How can I achieve this?
I am using the following code to solve and display output in html:
var r = nerdamer.solve(`1 - ${a} * x^(${p}) + ${b}`, 'x');
document.getElementById("polesAns").innerHTML= r.toString();
The folllowing is output:
[(138655807/135201312)*i+49385501/48155102,(-138655807/135201312)*i+49385501/48155102,(58886197/57419096)*i-49385501/48155102,(-58886197/57419096)*i-49385501/48155102,-560373381/386371730,172668482/119053157,(145619303/100403024)*i-5753750945848186/10000000000000000000000000000000,(-560373381/386371730)*i-5753750945848186/10000000000000000000000000000000]
There is no division performed also.
I tried the solution posted here:
How to use .toFixed() (or any alternative) on Nerdamer.solve solutions?
But how can I do this with my code? I tried the following:
var value = `1 - ${a} * x^(${p}) + ${b}`;
var toFixed = function(value, n) {
var img = Number(nerdamer.imagpart(value).text()).toFixed(n);
var real = Number(nerdamer.realpart(value).text()).toFixed(n);
// Format the number assuming i denotes imaginary in your case
var formatted = '';
if(real !== '0.0000') {
formatted += real;
}
if(img !== '0.0000') {
// Put the plus sign betweent the real and imaginary
if(img.charAt(0) !== '-' && formatted) {
formatted += '+';
}
// Assuming you're using i and not j for instance
formatted += img+'i';
}
return formatted;
};
sol_raw = this.nerdamer.solve(value,'s');
xs = this.nerdamer(sol_raw.toString()).each(function(solution) {
roundedSolutions.push(toFixed(solution, 4));
});
this.setState({
solution: roundedSolution.join(''),
equation:value})
document.getElementById("polesAns").value = solution.toString();
I don't understand the this.setState() part , should i declare sol_raw and xs as var?
Also the substitution of variable is used in the my above root equation from advice here javascript Solving equation with subsitution of variable value
thank you

Method implementation that takes 3 parameters and returns a binary number

I found a method that converts 1 number to a binary number.
function dec2bin(dec){
return (dec >>> 0).toString(2);
}
How to implement a method that takes 3 parameters (or more if possible) and turns them into one binary number.
for example:
Encrypt user with parameters
Age (up to 255-> 11111111)
Number of vacations (up to 15-> 1111)
On vacation or not (1 or 0)
create(30, 13, 1);
Expected to get 3 stacked together (00011110) (1101) (1): 0001111011011
According to your requirement Encrypt user with parameters age (up to 255-> 11111111), Number of vacations (up to 15-> 1111), On vacation or not (1 or 0)
const create = (age, noOfVacations, onVacation) => {
return (
age.toString(2).padStart(8, '0') +
noOfVacations.toString(2).padStart(4, '0') +
onVacation.toString(2).padStart(1, '0')
);
};
const ret = create(30, 13, 1);
console.log(ret);
By the way, you can refactor the above code to make it more reusable by making a separated binary to decimal with zero padding function.
const binToDecWithZeroPad = (param, n) => param.toString(2).padStart(n, '0');
const create = (age, noOfVacations, onVacation) =>
binToDecWithZeroPad(age, 8) +
binToDecWithZeroPad(noOfVacations, 4) +
binToDecWithZeroPad(onVacation, 1);
const ret = create(30, 13, 1);
console.log(ret);
If parameter number is unknown you can use rest parameter. Rest parameter syntax allows us to represent an indefinite number of arguments as an array. So you can use any number of parameter.
const create = (...params) => {
let str = '';
params.forEach((x) => (str += x.toString(2)));
return str;
};
const ret = create(30, 13, 1);
console.log(ret);
Update:
I have not to checked if the parameter is a non numeric, decimal or negative in my code because if you need to check it you can easily add it by using simple if condition and as for adding zero dynamically you cannot use more than one rest parameter because this is the limitation that only one rest parameter is allowed in the function declaration. Although, you can solve it by using one rest parameter(think about it if you have time). By the way, you can also use object, single or multiple array whatever you want as a parameter to make it dynamic.
This should work:
function dec2bin(dec){
return (dec >>> 0).toString(2);
}
function create(age, vacationNumber, vacation) {
var a = dec2bin(age).padStart(8, "0"); // padEnd adds zeros to match size
var b = dec2bin(vacationNumber).padStart(4, "0");
var c = vacation==true||vacation==1 ? 1 : 0;
return a + b + c;
}
console.log(create(15, 20, 1))
Here is a function encrypt that works on an array of any number of arguments, as long as you provide long enough encript digits array, and inputs are non-negative integers - if any of the conditions are not met, undefined is returned:
function dec2bin(dec, digits) {
if(typeof(dec)=="number" && dec%1==0 && dec>=0 && dec<Math.pow(2, digits))
return dec.toString(2).padStart(digits, "0");
return undefined;
}
function encrypt(userDetailsArray, encriptDigitsArray) {
if(userDetailsArray.length<=encriptDigitsArray.length) {
var result=(
userDetailsArray.map(
(detail, index) => dec2bin(detail, encriptDigitsArray[index])
)
);
if(result.includes(undefined))
return undefined;
else
return result.join("");
}
return undefined;
}
console.log(encrypt([30,13,1],[8,4,1])); /* your example */
console.log(encrypt([30,13],[8,4,1])); /* less input */
console.log(encrypt([30],[8,4,1])); /* even less input */
console.log(encrypt([30,13,1,100,5],[8,4,1,7,4])); /* more input and encript digits */
console.log(encrypt([999,13,1],[8,4,1])); /* bad input */
console.log(encrypt([30,13,1],[8,4])); /* not enough encript digits */
Decrypt (without testing validity of arguments):
function decrypt(bin, encriptDigitsArray) {
var result=[];
while(bin!="" && encriptDigitsArray.length) {
result.push(parseInt(bin.slice(0,encriptDigitsArray[0]), 2));
bin=bin.slice(encriptDigitsArray[0]);
encriptDigitsArray.shift();
}
return result;
}
console.log(decrypt("0001111011011",[8,4,1]));
console.log(decrypt("000111101101",[8,4,1]));
console.log(decrypt("00011110",[8,4,1]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Add 0 before single digit number of time format [duplicate]

This question already has answers here:
Adding "0" if clock have one digit
(9 answers)
Closed 3 years ago.
How can we add 0 before single digit number of time format.
Like if I have a time "0:3:25" (hh:mm:ss) format to convert into "00:03:25"
You shouldn't overcomplicate this:
const time = "0:3:25";
const paddedTime = time.split(':').map(e => `0${e}`.slice(-2)).join(':')
console.log(paddedTime)
split the string by semicolons (:), that yields an array (hours, minutes, seconds). map this array with a function that adds a 0 before every item in the array, and slice the last two digits (you get an array again). Then join the resulting array by semicolons (and you get a string).
Or you could use a regex instead of the split:
const time = "0:3:25";
const paddedTime = time.match(/\d+/g).map(e => `0${e}`.slice(-2)).join(':')
console.log(paddedTime)
The last part is the same with regex (map, slice, join).
And you also could use the padStart() (JavaScript built-in function):
const time = "0:3:25";
const paddedTime = time.split(':').map(e => e.padStart(2, 0)).join(':')
console.log(paddedTime)
padStart() on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
You can do something like below (Explanations included):
const time = '0:3:25';
const correctedTime = parseTime(time);
console.log(correctedTime);
function parseTime(time){
return time
.split(':') // Split them into array as chunk of [hour, minute, second]
.map(pad) // Map them with `pad` function below
.join(':'); // Join them back into 'hh:mm:ss'
}
function pad(n){
return parseInt(n) < 10 // If number less than 10
? '0' + n // Add '0' in front
: n; // Else, return the original string.
}
you can add split the existing time string on the ":", then for each portion, add the "0" then take the last two characters. Then simply join the portions back into a striung.
let time = "0:3:25";
function updateTime(){
let newTimePortions = [];
let timePortions = time.split(":");
timePortions.forEach(function(portion,index) {
newTimePortions[index] = ("0" + portion).slice(-2)
})
return newTimePortions.join(':')
}
console.log(updateTime()); // gives 00:03:25
Please try below code
var dateinfo="0:3:25";
var newdate=dateinfo.split(":");
var hdate=newdate[0];
var mdate=newdate[1];
var sdate=newdate[2];
if(hdate.length == 1 ){
hdate="0"+hdate;
}
if(mdate.length == 1 ){
mdate="0"+mdate;
}
if(sdate.length == 1 ){
sdate="0"+sdate;
}
dateinfo=hdate+":"+mdate+":"+sdate;
This is work for me

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);

Categories

Resources