regular express for number formatting - javascript

I'm not an expert on regex and I need some help on formatting numbers.
This is what I have:
TheNumber = TheNumber.toString().split(/(?=(?:\d{3})+(?:\.|$))/g).join(",");
Basically, I want TheNumber to be formatted with commas to separate thousands and up to 3 decimal precision with a dot to indicate decimal if there are decimals. It should also work with negative numbers.
I'm not far only that for the moment
3234234.223512 becomes 3,234,234.223,512
Thanks for your help.

I found this Javascript library accounting.js
As mentioned in description.
Accounting.js is a tiny JavaScript library for number, money and currency formatting, with optional excel-style column rendering (to line up symbols and decimals). It's lightweight, fully localisable and has zero dependencies.
It does the same as your requirements and even a little more.

I'd solve the problem in two pieces rather than a single regular expression. In particular, I'd:
remove the decimal point and any following numbers from the string first
User your reg exp (minus the decimal part) to add commas to the first part
concatenate back the removed decimal point

Related

reversed regex mashine implementation

I'm trying to match a string starting from the last character to fail as soon as possible. This way I can fail a match with a custom string cstr (see specification below) with least amount of operations (4th property).
From a theoritical perspective the regex can be represented as a finite state mashine and the arrows can be flipped, creating the reversed regex.
I'm looking for an implementation of this. A library/program which I can give the string and the pattern. cstr is implemented in python, so if possible a python module. (For the curious i-th character is not calculated until needed.) For anything other I need to do much more work because of cstr's calculation is hard to port to another language.
The implementation doesn't have to cover all latex syntax. I'm looking for the basics. No lookaheads or fancy stuff. See specification below.
I may be lacking common knowledge. Please do comment obvious things, too.
Specification
The custom string cstr has the following properties:
String can be calculated in finite time.
String has finite length
The last character is known
Every previous character requires a costly calculation
Until the string is calculated fully, length is unknown
When the string is calcualted fully, I want to match it with a simple regex which may contain these from the syntax. No look aheads or fancy stuff.
alphanumeric characters
uinicode characters
., *, +, ?, \w, \W, [], |, escape char \, range specifitation with { , }
PS: This is not a homework question. I'm trying to formulate my question as clear as possible.
OP here. Here are some thougts:
Since I'm looking for an unoptimized regex mashine, I have to build it myself, which takes time.
Alternatively we can define an upperbound for cstr length and create all strings that matches given regex with length < upperbound. Then we put all solutions to a tire data structure and match it. This depends on the use case and maybe a cache can be involved.
What I'm going for is python module greenery
from greenery import parse
pattern = parse.Pattern(...)
pattern.reversed()
...
this sometimes provieds a good matching experience. Sometimes not but it is ok for me.

i18n: How to localize big numbers and or large floating point numbers

In my JS app I have a very big number that could (or not) contain decimal places. An undetermined number of decimal places. A number like: -11212121332131343141456.12345678901234567.
So I can't use BigInt(number).toLocaleString(localeCode) because the number could contain decimal places. Also I can't use Intl.NumberFormat(localeCode).format(number) because at some point it will lose precision for being out of Number.MIN_SAFE_INTEGER and Number.MAX_SAFE_INTEGER range or having too many decimals.
How to deal with this scenario?
Target number could be splitted and parsed separately using BigInt.toLocaleString(...), then glued at the end. Special care should be taken with the decimal part, that should not contain group separator.
I faced this issue and developed this tiny library that helps you localize such numbers: NumberLocalizer

How to handle floating points in a JavaScript calculator?

Why is this not a duplicate of these great SO articles?
While the two posts linked in the comments below are excellent I am specifically looking for information that helps me to address this issue in native JS. I know that JS shouldn't be the first choice for complex math, but given the limitation that this calculator is meant to run in the browser it is the tool that I have decided to work with.
Background
I'm trying to make a calculator with TypeScript without any libraries (like Big.js) and without using string concatenation in the inner logic of the calculator.
Examples
When a user wants to type the number 8.5:
The 8 key is pressed
The decimal key is pressed
The 5 key is pressed
Mathematically I create this number in the display with the following snippet:
8 + 5 * 0.1
This works but if I continue down the decimal places I encounter something unexpected:
8.5 + 5 * 0.01 // 8.55
8.55 + 5 * 0.001 // 8.555000000000001
Question
What is the best way to handle this without converting the number to a string? Is there an intelligent way to impose a limit on the precision of the calculator so that it only supports accuracy to so many decimal places?
Thanks for your help!
Use .toFixed():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
or .toPrecision():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision
depending on your needs.
Note that you don't need to convert numbers all the time. The only place to convert - is for the final output to the view. In this case we can even leave it in string format.
That is an answer to the question "how to get manage with" (like in description). About "why do we get such result" - first comment provides great answer.
The easiest way to get the Number value that is closest to what the user enters is to build a numeral in a string from the user’s keypress and then convert them with String.toNumber().
Numbers such as 8.55 or 8.555 are not exactly representable in the Number format. The closest values are 8.550000000000000710542735760100185871124267578125 and 8.55499999999999971578290569595992565155029296875. Converting the strings “8.55” and “8.555” with .toNumber() should produce these values.
Because these are the closest representable values, no calculation or algorithm can produce any closer values in the Number format.
For simple additions, subtractions, and limited multiplications, you can mimic decimal arithmetic by rounding to a desired number of decimal digits after each Number operation. However, this is generally not a feasible approach because other operations and various sequences of operations will exceed the ability to mimic decimal arithmetic reasonably.

Why is parseInt() not converting my String of numbers correctly?

I have some logic within a function that takes a string of numbers called digits like so:
6145390195186705543
I then attempt to convert with parseInt() like so:
parseInt(digits)
The result of:
digits = parseInt(digits);
is
6145390195186705000
Can someone help me understand why this is the case? and how i can get an accurate conversion?
This is another version of "broken" floating point math: Javascript uses 64 bits to store numbers as small as the size of an atom up to the number of atoms in the universe. As that is quite a broad range it cannot be stored accurately, therefore the numbers are stored in an imprecise way but can represent a very broad range. In your case 6145390195186705000 is the inaccurate version JS is able to store as 6145390195186705543 cannot be stored.
and how i can get an accurate conversion?
You cannot store an "accurate number", therefore you cannot convert it accurately. However there are some libraries that allow you to work with strings as if they were numbers, such as BigIntJS.
As this is a common problem, this is going to be solved in the next JS version, see this proposal. You can currently test it in the new version of chrome.

converting LARGE string to an integer [duplicate]

How do I parse a 20-digit number using JavaScript and jQuery?
A 20-digit number is generally too big for a JavaScript native numeric type, so you'll need to find a "big number" package to use. Here's one that I've seen mentioned on Stack Overflow and that looks interesting: http://silentmatt.com/biginteger/
That one is just integers. If you need decimal fractions too, you'll have to find something else.
If you just want to check that a 20-digit string looks like a number, and you don't need to know the value, you can do that with a regular expression.
You can't have a 20-digit number in JavaScript - it'll get floated off on you.
You can keep 20 digits (or 200 or 2000) intact as a string, or as an array of digits, but to do any math on it you need a big integer object or library.
Normally you use Number() or parseInt("", [radix]) to parse a string into a real number.
I am guessing you are asking about what happens when the string you parse is above the int - threshold. In this case it greatly depends on what you are trying to accomplish.
There are some libraries that allow working with big numbers such as https://silentmatt.com/biginteger/ - see answer - (did not test it, but it looks OK). Also try searching for BigInt JavaScript or BigMath.
In short: working with VERY large number or exact decimals is a challenge in every programming language and often requires very specific mathematical libraries (which are less convenient and often a lot slower than when you work in "normal" (int/long) areas) - which obviously is not an issue when you REALLY want those big numbers.

Categories

Resources