Javascript - Calculation Error [duplicate]
In the Chrome Javascript Console I type the following:
开发者_开发知识库3.1 * 3.68
And the result returned is:
11.408000000000001
Why is the result not:
11.408
Floating point errors are quite normal, this is due to the problems inherent in representing some floating point numbers in binary.
Read this: What Every Computer Scientist Should Know About Floating-Point Arithmetic.
The reason for the 'funny' result is because of inexact floating point representation internally of certain numbers. While 3.1 * 3.68 results in 15 decimals, both 3.11*3.68 and 3.1*3.67 give the expected 4 decimals and 3 decimals respectively.
In practice, this javascript 'bug' can result in rounding error when the expected result has 3 decimals such as .745 and the floating point result has .744999999999999. Example: 1.9*3.55=6.744999999999999 (should be 6.745). For financial statements, javascript program will gives 6.74 instead of the expected rounding of 6.75. A big headache for accounting reconciliation even though it happens less than 1 in 1000 cases.
One way to get the exact results is for a javascript programmer to post-process the result as in:
var r=1.9*3.55; r=r.toFixed(3); //=6.745, knowing that the results should be 3 decimals r=r.toFixed(2); // round to 2 decimals
It is unfortunate that no javascript engine today can do this little easy step to arrive at the expected result. To guarantee an exact decimal arithmetic (at least for financial use as opposed to scientific or astronomical use), all javascript engine need to do is to determine n=(# of decimals in the result) then do toFixed(n) on the internal floating point result.
you can use toFixed method of javascript more detail:
Method of Number
Implemented in JavaScript 1.5
ECMAScript Edition ECMAScript 3rd Edition
Syntax
number.toFixed( [digits] )
Parameter
digits The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0.
Returns
A string representation of number that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If number is greater than 1e+21, this method simply calls Number.toString() and returns a string in exponential notation.
Throws
RangeError If digits is too small or too large. Values between 0 and 20, inclusive, will not cause a RangeError. Implementations are allowed to support larger and smaller values as well. TypeError If this method is invoked on an object that is not a Number.
for your problem use (3.1 * 3.68).toFixed(3); //11.408
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toFixed
精彩评论