I want to write a function that looks like this:
function getValuesGreaterThan(num, values);
It'll return an array of the values.
Normally this is straightforward, but the values are stored in an array of strings: [..., "1643764147.7500000000", "1643764147.7600000000382333388888", "1643764147.7700000000", ...]
. I want to make sure the output of getValuesGreaterThan
isn't affected by precision issues or coercion quirks.
These decimal numbers come from a system call to a bash shell then are read in as strings. Sometimes these numbers are beyond the limitations of JavaScript Number
s:
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.
I've learned that JavaScript has a BigInt type, but I can't find anything about a BigReal
or a BigDecimal
, etc. This question spawned from a similar question of mine (as an aside, there are some examples of what I've tried there), and a comment informed me that there are libraries for this:
With a quick search I've found decimal.js, bignumber.js and math.js which seem could do the job.
But given that I only need the comparison operators (technically, I only need >
), I'm wondering if there is an easy way to implement a solution without adding a library*.
How do I compare large decimal numbers in JavaScript?
*: One of the reasons I want to avoid libraries is because my getValuesGreaterThan
code runs as a bash script with a #!/usr/bin/env ts-node
shebang at the top. Adding a library would require bringing in a package.json
a node_modules
dir, potentially a tsconfig.json
, etc. If I could compare large decimals in vanilla JS/TS, it avoids a lot of boilerplate.