• Status: Solved
• Priority: Medium
• Security: Public
• Views: 477

# Can I override the default * function in javascript with a more accurate multiply?

I've recently noticed how the default multiplication in javascript uses floats, which, in something like the following  .7 * 1.3 * .5 = .45499999999999 which when rounded to 2 decimals = .45 instead of .46 which is what it should be if you use a calculator...

Is it possible to replace/override the math functions so that when you do something like .7 * 1.3 it automatically multiplies it by 1000 and divides by 1000 then again when it multiplies by .5 to insure that the decimals are always kept exact?

Ideally I'm looking for a solution that fixes potentially over a 100 calls in a large app without having to go through each function and fixing them.
0
1 Solution

Commented:

It is looking like overriding operators is not fully implemented in Javascript.  This outlines an option library that can be installed, but may not work on a wider basis.  There is a proposal for Javascript2 to implement this, but several security arguments against.  See http://ajaxian.com/archives/operator-overloading-in-javascript-2-and-a-potential-monster-csrf-hole
There is a blog referenced in there about the actual security leak.  However, currently there is no means of doing it.  Your best bet is to create a function and use that in place of the operator.

Good luck on this,

Geoff
0

Commented:
There is a VERY easy way to do this which hardly anyone thinks of.  Multiply all values by one million, then multiply those values, and thentake the product of the multiplication, and process it yourself down to as many decimal places as you want, limited by 12 to 20 decimals.  Don't use built in rounding functions, search the string to the decimal places you want, PLUS three, and make your own decision on rounding.  Too easy!
0

Author Commented:
Actually scrathcyboy, thats why I wanted to override the multiplication function.  Wouldn't it be awesome to change all the * to multiply everything by a million then divide back by the million rounded however I want for the entire site?  Then we could write standard javascript but have the site accurate to the level we wanted.  So anyways, the solution to accurate javascript is easy, the solution to fixing an entire intranet in one fell swoop is less so. :(
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.