How can numbers be shortened? For instance, changing 1,000,000 to 1M, 1,000 to 1k, and 10,000 to 10K.
How can numbers be shortened? For instance, changing 1,000,000 to 1M, 1,000 to 1k, and 10,000 to 10K.
For those who are utilizing a JavaScript library or framework (like angular, react), consider incorporating the following:
Consider giving this a try:
tryNum(num) { if(isNaN(num)) return num;
if(num < 9999) {
return num;
}
if(num < 1000000) {
return Math.round(num/1000) + "K";
}
if( num < 10000000) {
return (num/1000000).toFixed(2) + "M";
}
if(num < 1000000000) {
return Math.round((num/1000000)) + "M";
}
if(num < 1000000000000) {
return Math.round((num/1000000000)) + "B";
}
return "1T+";
}
If you're looking to achieve a similar result, one approach could be:
function shortenNumber(num, decimalPlaces) {
if (isNaN(num)) {
console.log(`${num} is not a valid number`)
return false;
}
const magnitudes = {
none: 1,
k: 1000,
M: 1000000,
G: 1000000000,
T: 1000000000000,
P: 1000000000000000,
E: 1000000000000000000,
Z: 1000000000000000000000,
Y: 1000000000000000000000000
};
const suffix = String(Math.abs(num)).length <= 3 ?
'none' :
Object.keys(magnitudes)[Math.floor(String(Math.abs(num)).length / 3)];
let shortenedNum
if (decimalPlaces && !isNaN(decimalPlaces)) {
const roundValue = Math.pow(10, decimalPlaces)
shortenedNum = Math.round((num / magnitudes[suffix]) * roundValue) / roundValue
} else {
shortenedNum = num / magnitudes[suffix];
}
return String(shortenedNum) + (suffix !== 'none' && suffix || '');
}
// example usage
console.log('1:', shortenNumber(1));
console.log('12:', shortenNumber(12));
console.log('198:', shortenNumber(198));
console.log('1278:', shortenNumber(1278));
console.log('1348753:', shortenNumber(1348753));
console.log('7594119820:', shortenNumber(7594119820));
console.log('7594119820 (rounded to 3 decimal places):', shortenNumber(7594119820, 3));
console.log('7594119820 (invalid rounding value):', shortenNumber(7594119820, 'foo'));
console.log('153000000:', shortenNumber(153000000));
console.log('foo:', shortenNumber('foo'));
console.log('-15467:', shortenNumber(-15467));
console.log('0:', shortenNumber(0));
console.log('-0:', shortenNumber(-0));
I attempted to create a selenium test that verifies if navigating from one page to another occurs successfully when clicking on buttons. Initially, the test checks if clicking a button on the old page leads to navigation to a new page. Then, it verifies if ...
When I click a button, a pie chart is generated using chartjs. The results are displayed based on the filters applied, showing (Name | Value%): Service_1 | 10 Service_2 | 15 Service_3 | 75 Sometimes, certain results may not appear: Service_1 | 20 S ...
Is there a JavaScript equivalent for the str.decode('string_escape') function in Python? var data = {k: 'test\\"ing\\:"'}; JSON.stringify(data).decode('string_escape') >>> '{"k": "test"ing""} ...
Currently, I am facing an issue with loading images into a canvas element as the image seems to be scaled in some way. To provide some context, I have multiple canvases on my webpage and I want to load images into them. Since the dimensions of the canvas ...
Is it possible to create an extendable parent class with a generic type in JavaScript, similar to how it's done in Java? public class Parent<T> { private T t; public T get() { return t; } ... If so, what would the child class l ...
I need to check for duplicate values in an array element. Within my array, I have multiple objects like {S:1,R:2,V:3}. My goal is to display an alert message if there are duplicate values for the "S" element in that array. My Approach: var arr=[{S:1,R:2 ...
Here is the code I have written: projectDependencies.forEach((val)=> { container.register(val[0],function () { return require(val[1]); }); }); When I execute the command nodemon server.js, I encounter the following error: Error: c ...
Just starting out with coding and I need help making this formula work. GPro = 31 * ((Cr / 8.4)-1.5) * (kA-0.2) * kG I have an online calculator set up to update automatically when the user inputs data (on keyup event). The site has three formulas - Crum ...
Here is the function I'm working with: function toggleDiv() { let targetDiv = document.getElementById('targetDIV') if (targetDiv.style.display === 'none') { targetDiv.style.display = '' } else { targetDi ...
Mobile browsers such as Safari have a tendency to ignore large files when passed in through the <input type="file">. For example, testing with a 10mb image file results in no trigger of any events - no change, no error, nothing. The user action is si ...
While browsing through , I found some fantastic animations that inspired me. The animations at the header seem to be standard CSS animations with delays. However, as you scroll down and other sections become visible, the animations reappear only once. Can ...
I have encountered an issue with my PDF function where using multiple tables and the didDrawPage() hook to add headers and footers results in images being drawn multiple times in the header due to the multiple tables. To resolve this, I created a separate ...
I am currently working on developing a 2D, top-down RPG game inspired by Zelda for the web... My plan is to organize dialog in JSON format... Right now, I have the JSON data stored in an external JavaScript file called js/json.js: function getJson() { ...
Picture a typical web application page that utilizes jQuery and Knockout to create modal dialogs for data editing. The process runs smoothly as the page loads, with the JS generating the dialogs when buttons are clicked. However, there is a slight issue wh ...
I'm currently developing a boxing game that allows users to select from three different boxers. The computer will then choose one of the remaining two boxers that the user did not select. https://jsfiddle.net/1ehpxto6/ My HTML code looks like this: ...
I've successfully set up an API with Django Rest Framework that functions well when accessed through cURL, HTTPie, or the browsable API. The API utilizes token authentication, requiring initial credentials to obtain a token. To achieve this using HTTP ...
I recently switched from using Cola to fCose in Cytoscape.js for graphing multiple graphs with no connections. With Cola, I was able to manually set node positions by tweaking the layout options. However, with fCose, despite adjusting variables like quali ...
I'm dealing with a React/Express setup that looks something like this (simplified for clarity): const path = require('path') const express = require('express') const CLIENT_BUILD_PATH = path.join(__dirname, '../build') ...
I'm in the process of transitioning a project to Vue, and I'm curious about how I can dynamically assign classes to specific elements based on database values rendered with Vue. Previously, I had this code set up without Vue: $(document).ready(f ...
In my JavaScript code, I have an event set to trigger at regular time intervals that clicks on a specific ASP button. This event is part of a chat room application where the gridview inside a panel needs to be refreshed frequently to display new chats. H ...