Ok, so we all know of the floating point number problem, such as:
0.23 - 1 + 1 = 0.22999999999999998
And since in javascript, unlike other languages, all numbers are actually floating points and there's no int/decimal there are all kinds of libraries and workarounds such as BigDecimal to handle this problem. This is best discussed here.
I was creating a "numeric spinner" control that supports floating point numbers, and obviously I wouldn't want the user to click "up" and then "down" and get a different number from what he started with, so I tried writing a workaround - a "addPrecise" method of sorts.
My idea was the following:
- Take the two numbers I'm about to add, and figure out their "precision" - how many digits they have after the decimal point.
- Add the two numbers as floats
- Apply
toFixed()
on the result with the max precision of the two
For example:
float #1: 1.23
float #2: -1
adding them normally would result in 0.22999999999999998
but if I'm taking the maximal number of decimal places, which is #1's 2 digits, and apply toFixed(2)
I get 0.23
as I wanted.
I've done this with the following piece of code but I'm not happy with it.
function addPrecise(f1, f2){
var floatRegex = /[^\d\-]/;
var f1p = floatRegex.exec(f1.toString()) ? f1.toString().split(floatRegex.exec(f1.toString()))[1].length : 0;
var f2p = floatRegex.exec(f2.toString()) ? f2.toString().split(floatRegex.exec(f2.toString()))[1].length : 0;
var precision = Math.max(f1p,f2p);
return parseFloat((parseFloat(f1) + parseFloat(f2)).toFixed(precision));
}
(It's worth noting that I'm using the regex to find the 'floating point' because in other locales it might be a comma instead of a period. I'm also taking into account the possibility that I got an Int (with no point) in which case it's precision is 0.)
Is there a cleaner/simpler/better way to do this?
Edit: I'd also like to point out that finding a reliable way to extract the number of decimal digits is also part of the question. I'm unsure about my method there.