PRB: Multiplication Errors in JScript

ID: Q244699


The information in this article applies to:
  • Microsoft JScript, versions 2.0, 3.0, 4.0, 5.0


SYMPTOMS

When performing multiplication in JScript, some operands can produce a seemingly inordinately large loss of precision. An example of this might be multiplying 9.2 and 100 and getting a result of "919.9999999..."


CAUSE

JScript is Microsoft's implementation of ECMAScript as defined in the ECMAScript Language Specification, ECMA-262. Section 11.5.1 (for multiplication) and 11.5.2 (for division) of ECMA 262 states that the result of a floating point multiplication should be governed by the rules of IEEE 754 (specifically section 4.1 - "Round to Nearest").

The ECMA specification mandates that ECMAScript display as much precision as possible when displaying floating point numbers as strings. That is, in JScript you are guaranteed to lose no data when you convert back and forth between string and binary representations. When trying to multiply 9.2 by 10.0, 10.0 can be exactly represented as a floating point number because it's an integer, but 9.2 cannot. You can't represent 92/10 exactly in base two any more than you can represent 1/3 exactly in base 10. So when converting from the string "9.2" to the internal binary representation, a tiny error is accrued.

However, the binary string that represents 9.2 internally is the binary value closest to 9.2 and the algorithm that converts back and forth between strings and binary representation will round-trip; that is, that binary representation will be converted back to 9.2.

Ultimately, this is an issue because we human beings see numbers like "920" as special. If you multiply 3.63874692874 by 4.2984769284 and get a result that is one-billionth off, is not all that obvious, but when you multiply 9.2 by 10.0 and get a result that is one-billionth off, it seems that this is a greater loss of precision. The computer doesn't know that 9.2 is more special than 3.63874692874; it uses the same lossy algorithms for both.


STATUS

This behavior is by design.


MORE INFORMATION

Create the following simple HTML page:


<HTML>
<HEAD>
<SCRIPT language="jscript">
function multiply()
{
   alert(9.2 * 100);
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT type="button" value="What is the value of 9.2 * 100 in JScript?" onclick="multiply();">
</BODY>	
</HTML> 
When the button is clicked, a message box appears giving the result "919.9999999999999".


REFERENCES

ECMAScript Language Specification
IEEE 754 - "IEEE Standard for Binary Floating-Point Arithmetic"

Fore more information on scripting, see the Microsoft Scripting Page.

Additional query words:

Keywords : kbScript kbGrpInet kbDSupport
Version : WINDOWS:2.0,3.0,4.0,5.0
Platform : WINDOWS
Issue type : kbprb


Last Reviewed: January 21, 2000
© 2000 Microsoft Corporation. All rights reserved. Terms of Use.