I have an input of two strings, each of which representing a non-negative rational number in decimal format.
Given these two strings x and y, I would like to check if the numeric value represented by x is larger than the numeric value represented by y.
These two values can be very large, as well as to extend to a very high precision (i.e., many digits after the decimal-point).
As such, I cannot rely on Number(x) > Number(y) to do the job.
Instead, I have implemented the following function:
function isLarger(x, y) {
const xParts = x.split(".").concat("");
const yParts = y.split(".").concat("");
xParts[0] = xParts[0].padStart(yParts[0].length, "0");
yParts[0] = yParts[0].padStart(xParts[0].length, "0");
xParts[1] = xParts[1].padEnd (yParts[1].length, "0");
yParts[1] = yParts[1].padEnd (xParts[1].length, "0");
return xParts.join("").localeCompare(yParts.join("")) == 1;
}
I have conducted extensive testing, by generating random input x and y, and comparing the result of isLarger(x, y) to the value of the expression Number(x) > Number(y).
Of course, for the reasons mentioned above, I cannot rely on the value of the expression Number(x) > Number(y) to be correct for every possible input x and y.
So I would like some kind of feedback on the function above:
- Does it have any caveats in it?
- Is there perhaps a simpler way of achieving this?