JS computing problems

Source: Internet
Author: User

The problem is as follows:
37.5*5.5 = 206.08 (JS calculates this result. I rounded it to two decimal places)
I first suspected it was a rounding problem, and I used js to calculate a result: 206.08499999999998.
How can this happen? How can we multiply two digits with only one decimal number.
I Googled and found that this was a bug in Javascript floating point operations.
For example, 7*0.8 Javascript is calculated as follows: 5.6000000000000005
Some solutions have been found on the Internet, that is, some floating point operation functions have been re-written.
The following is an excerpt from these methods for your reference:

Program code

// Division function, used to obtain accurate division results
// Note: the division result of JavaScript has an error, which is obvious when two floating point numbers are separated. This function returns a more precise division result.
// Call: accdiv (arg1, arg2)
// Return value: the exact result of dividing arg1 by arg2

function accDiv(arg1,arg2){ var t1=0,t2=0,r1,r2; try{t1=arg1.toString().split(".")[1].length}catch(e){} try{t2=arg2.toString().split(".")[1].length}catch(e){} with(Math){ r1=Number(arg1.toString().replace(".","")) r2=Number(arg2.toString().replace(".","")) return (r1/r2)*pow(10,t2-t1); } } 

 

// Multiplication function, used to obtain accurate multiplication results
// Note: there is an error in the Javascript multiplication result, which is obvious when two floating point numbers are multiplied. This function returns a more accurate multiplication result.
// Call: accmul (arg1, arg2)
// Return value: the exact result of multiplying arg1 by arg2

function accMul(arg1,arg2) { var m=0,s1=arg1.toString(),s2=arg2.toString(); try{m+=s1.split(".")[1].length}catch(e){} try{m+=s2.split(".")[1].length}catch(e){} return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m) } 

 

// Addition function, used to obtain accurate addition results
// Note: The addition result of JavaScript has an error, which is obvious when two floating point numbers are added. This function returns a more accurate addition result.
// Call: accadd (arg1, arg2)
// Return value: the exact result of adding arg2 to arg1

function accAdd(arg1,arg2){ var r1,r2,m; try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0} try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0} m=Math.pow(10,Math.max(r1,r2)) return (arg1*m+arg2*m)/m } 

 

Post the code for subtraction:

Function subtr (arg1, arg2) {var R1, R2, m, n; try {R1 = arg1.tostring (). split (". ") [1]. length} catch (e) {R1 = 0} Try {r2 = arg2.tostring (). split (". ") [1]. length} catch (e) {r2 = 0} M = math. pow (10, math. max (R1, R2); // last modify by deeka // dynamic control precision length n = (r1> = R2 )? R1: R2; Return (arg1 * m-arg2 * m)/m). tofixed (n );}

 

 

JS method explanation

Pow Method

Returns the specified power of the base expression.

Math.pow(base, exponent)

Parameters

Base

Required. The Base Value of the expression.

Exponent

Required. The exponential value of the expression.

Example

In the following exampleBaseexponentThe return value is 1000.

Math.pow(10,3);
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <HTML xmlns = "http://www.w3.org/1999/xhtml"> 

 



Tofixed Method

Returns a string representing a number in fixed-point notation.

numObj.toFixed([fractionDigits])

Parameters

Numobj

Required. OneNumberObject.

Fractiondigits

Optional. The number of digits after the decimal point. The value must be between 0 and 20, including 0 and 20.

Description

TofixedReturns a string of numbers in fixed-point notation. This string contains a valid number before the decimal point, and must containFractiondigitsNumber.

If noFractiondigitsParameter, or this parameter isUndefined,TofixedThe method assumes that the value is 0.

The tofixed method is often used when writing scripts to process numbers.

I. What can tofixed do?

The following is an introduction from the network's tofixed:

Tofixed method:

Returns a string representing a number in fixed-point notation.

numObj.toFixed([fractionDigits])

Numobj

Required. OneNumberObject.

Fractiondigits

Optional. The number of digits after the decimal point. The value must be between 0 and 20, including 0 and 20.

Description

TofixedReturns a string of numbers in fixed-point notation. This string contains a valid number before the decimal point, and must containFractiondigitsNumber.

If noFractiondigitsParameter, or this parameter isUndefined,TofixedThe method assumes that the value is 0.

2. Can tofixed be rounded down?

The answer is yes. But this is also the problem. This rounding is unstable (different browsers are different ).

(1 ).

In IE7, 0.00 is displayed when you click the button, and FF is 0.01.

(2)

Both IE and FF are normal.

It can be seen that for IE, some numbers cannot be correctly rounded to the correct result when tofixed is used. This problem may not be realized by many friends, but it is a small problem, but sometimes it will cause adverse consequences.

Like the example 0.009.tofixed (2) above (0.009 is the result of a series of processing operations), I just met. In one page, 1% is displayed because of the computation performed in the background code, while in another page, 0% is displayed because the tofixed result is used. Therefore, it was approved by the customer.

Okay. How can this problem be solved?

Iii. Alternative solutions:

As many friends think, we can rewrite this method:

Number. Prototype. tofixed = function (Fractiondigits)...

The following provides a simple solution:

Code
Number. Prototype. tofixed = function (fractiondigits)
{
// Fractiondigits is not processed. Assume it is a valid input.
Return (parseint (this * Math. Pow (10, fractiondigits) + 0.5)/Math. Pow (10, fractiondigts). tostring ();
}

The following is an example of overwrite tofixed:

Code
<HTML>
<Head>
<SCRIPT type = "text/JavaScript">
Number. Prototype. tofixed = function (s)
{
Return (parseint (this * Math. Pow (10, S) + 0.5)/Math. Pow (10, S). tostring ();
}
</SCRIPT>
</Head>
<Body>
<Input onclick = "alert (0.009.tofixed (2)" type = "button" value = "display 0.009.tofixed (2)">
</Body>
</Html> with statement

Set the default object for the statement.

with (object)
   statements

Parameters

Object

New default object.

Statements

One or more statements,ObjectIs the default object of the statement.

Description

WithThe statement is usually used to shorten the amount of code that must be written in a specific situation. In the following example, note thatMathReuse:

x = Math.cos(3 * Math.PI) + Math.sin(Math.LN10) y = Math.tan(14 * Math.E)

When usingWithStatement, the Code becomes shorter and easier to read:

with (Math){   x = cos(3 * PI) + sin (LN10)     y = tan(14 * E)}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.