Format Number With Commas [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have built a function that formats a number using commas, similar to what the toLocaleString method does. To achieve that, I used a regular expression and recursion. However, I have a feeling that this could've been done better.
I did some research but was not able to find the answer I'm looking for. So, my question is...Is there a better way to do this?
function transform(value) {
const pureNumber = parseInt(value);
const numberParts = [];
function format(val) {
let formatted = val.toString().split(/(\d{3})$/).filter(i => !!i).join(",");
const splitted = formatted.split(",");
if(splitted.length > 1){
numberParts.unshift(splitted[1]);
return format(splitted[0]);
}
numberParts.unshift(splitted[0]);
return numberParts.join(",");
}
return format(pureNumber.toString());
}
const data = "1234567890";
const result = transform(data);
console.log(result);
What I need you to note is that I used a regular expression to split the string, however, I was wondering if there is a way to only use regular expressions to avoid the recursion? I.e., Is there a way to use the regular expression starting at the end of the string and repeating towards left?

This can be accomplished much simpler using a single Regex expression:
function transform(value) {
return String(value).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
// Works with string
console.log(transform("0123456789"));
// And numbers
console.log(transform(1234567890));
This regex will look in the string for any point that has 3 digits in a row after it and will make sure that point only has exactly multiples of 3 digits.
This was discovered in the first part of a post:
How to print a number with commas as thousands separators in JavaScript

Related

How to verify huge number in JS [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 10 months ago.
Improve this question
I have a task to filter out a number which is bigger than 9e+65 (65 zeros).
As input I have a number and as output I need to return a boolean value. The function can accept regular formatted numbers (42342) and any scientific notation (1e5).
My approach is:
const 65zerosCheck = (num: number):boolean =>
num.toString().includes("e+")
: Number(value.toString().split('e+')[1]) > 65
: false
It looks dirty and the reviewer didn't accept it.
To quote MDN:
In JavaScript, numbers are implemented in double-precision 64-bit binary format IEEE 754 (i.e., a number between ±2^−1022 and ±2^+1023, or about ±10^−308 to ±10^+308, with a numeric precision of 53 bits). Integer values up to ±2^53 − 1 can be represented exactly.
You do not have to worry about such huge numbers. I have added a link to MDN quote above at the end of this snippet where it is discussed in details about how Javascript handles Numbers.
const HUGE_NUMBER_THRESHOLD = 9e+65;
const checkHugeNumbers = (num) => num > HUGE_NUMBER_THRESHOLD;
let myTestNum = 9000000000000000000000000000000000000000000000000000000000000000000;
console.log(checkHugeNumbers(myTestNum));
// OUTPUT:
// true
For further study, here is the reference link.
There doesn't seem to be anything logically wrong with your approach, but if your reviewer is asking for a cleaner approach, this is my suggestion.
It does the same thing, but is more readable and its easy to add on to, in the future. Splitting up the logic and results into descriptive variables makes it easier to read, and catch any errors or oversights that may be encountered.
Also you can save a step by directly getting the index, without using split and creating three types (array, string, and number), that can make it confusing to follow. This approach keeps everything between strings and numbers
const checkOver65Zeros = (num: number) =>{
const numString = num.toString()
const idxOfZeros = numString.indexOf("e+")
if(idxOfZeros!== -1)
return Number(numString.substring(idxOfZeros + 2)) > 65
return false
}
console.log(checkOver65Zeros(900000000000000000000000000000000000000))

Function that transforms a string of upvote counts into an array of numbers in JavaScript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
What is the best possible way to create a function that transforms a string of upvote counts into an array of numbers. Each k represents a thousand.
transformUpvotes("6.8k 13.5k") ➞ [6800, 13500]
transformUpvotes("5.5k 8.9k 32") ➞ [5500, 8900, 32]
transformUpvotes("20.3k 3.8k 7.7k 992") ➞ [20300, 3800, 7700, 992]
Return the upvotes as an array.
Now i tried to do this myself with or without regex, the pattern i used was this /\.\d(k)/g
I first converted the string into a javascript array using array.split(' '); but i don't know how to replace the k with zeroes properly so that the k after floating point get two zeroes and a k without floating point get three zeroes.
function transformUpvotes(upvotes) {
return upvotes.split(" ").map(x => {
parsed = parseFloat(x);
return x.endsWith("k") ? parsed * 1000 : parsed;
});
}

how to get all number from beginning of string until first non-number? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
How to get all number from beginning of string until first non-number?
For example, I want to get 12345 from '12345abc' and another example get 5678 from '5678kkk'.
Is any way can do this?
You could use RegExp#match with ^ anchor, to find out the numeric characters from beginning:
const string = "12345abc";
const matches = string.match(/^\d+/);
// Fallback if no matches found
const numbers = (matches || [])[0];
console.log(numbers);
Use parseInt() as it will stripe out all the characters other than the numeric character so you do not need custom logic for getting the numeric value as you have described:
console.log(parseInt('12345abc'));
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
Use parseInt
let str = '5678kkk';
console.log(parseInt(str));

Change characters in a string by slicing in Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a little question. Can i in javascript use string.slice() = x?
Example: "Hello world!".slice(2,3) --> = x <-- can I use this?
^ the 3rd character in the string
So, can i change characters with a slice? (:
No, you can not assign a value to a part of a string:
Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string.
You can split the string into an array of characters, change the wanted character at the given index and join the array for a new string.
var string = "Hello world!",
array = string.split('');
array[2] = 'X';
string = array.join('');
console.log(string);
Yes you can use slice to get the character.
var x = "Hello world!".slice(2,3);
console.log(x);
However, you can't change character with a slice. See Nina's answer how to do that.

Match 11 or 13 digits using regex [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am writing a code where I am receiving a number of exactly 11 or 13 digits in it. But, the problem is that it may contain some hyphens at random places.
Can anyone suggest a regular expression for this?
Sample inputs (assuming only 5 digits):
1. 12345
2. 1-234-5
3. 12-34-5
4. 123-45
5. 1-2-34-5
Try this code snippet. It may help you.
var str="123-45";
str.replace( /\D+/g, '');
Here,
\D - Find a non-digit character.
so, Code will replace non-digit with ''.
It would be significantly easier, and infinitely more readable to remove all dashes, and then count the remaining characters.
var str = "1-234-5";
var res = str.replace(/-/g, '').length;
if(res === 11 || res === 13) {
//do whatever
}
Have a try with:
^(?:-?\d){11}(?:-?\d-?\d)?$
or, if - can't be in first place:
^(?:\d-?){11}(?:\d-?\d)?$

Categories