JavaScript floating-point arithmetic and comparison code collection and collation

Source: Internet
Author: User
Tags mul

The following code goes from: http://segmentfault.com/a/1190000000324193

Floating-point addition:

The/** **  addition function, which is used to obtain the exact addition  **  explanation: the addition result of JavaScript will be error, which will be obvious when the two floating-point numbers are added. This function returns a more accurate addition result.  **  Call: Accadd (ARG1,ARG2)  **  return value: Arg1 plus arg2 precise results  **/function accadd (arg1,  ARG2)  {        var r1, r2, m, c;         try {        r1 =  Arg1.tostring (). Split (".") [1].length;    } catch  (e)  {         r1 = 0;    }        try {         r2 = arg2.tostring (). Split (".") [1].length;    } catch  (e)  {         r2 = 0;    }    c = math.abs (r1 -  R2);     m&Nbsp;= math.pow (10, math.max (R1, R2));        if  ( c > 0)  {                 var cm = math.pow (10, c);                 if  (R1 > R2)  {             arg1 = number (Arg1.tostring (). Replace (".",  "")) ;             arg2 = number (arg2.toString (). Replace (".",  ""))  * cm;        } else {             arg1 = number (Arg1.toString ( ). Replace (".",  ")")  * cm;             arg2 = Number (arg2.tostring (). Replace (".",  ""));        }     } else {        arg1 = number ( Arg1.tostring (). Replace (".",  ""));         arg2 = number (Arg2.tostring (). Replace (".",  ""));    }         return  (ARG1 + ARG2)  / m;} Adding an Add method to the number type makes it more convenient to call. number.prototype.add = function  (ARG)  {         Return accadd (arg, this);};

Floating-point number subtraction:

/** **  subtraction function, used to get the exact subtraction result  **  explanation: JavaScript subtraction results will be error, when the two floating-point number subtraction will be more obvious. This function returns a more accurate subtraction result.  **  Call: Accsub (ARG1,ARG2)  **  return value: Arg1 plus arg2 precise results  **/function accsub (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 accuracy Length     n =  (R1 >= R2)  ? r1 : r2;     return  ((arg1 * m - arg2 * m)  / m). toFixed (n);}   Adds a Mul method to the number type, which is more convenient to call. number.prototype.sub = function  (ARG)  {    return accmul (ARG,  this);};

Floating-point multiplication:

/** **  multiplication function, which is used to get the exact multiplication result  **  explanation: The result of JavaScript multiplication will be error, it will be more obvious when two floating-point numbers multiply. This function returns a more accurate multiplication result.  **  Call: Accmul (ARG1,ARG2)  **  return value: arg1 times the exact result of  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);}   Adds a Mul method to the number type, which is more convenient to call. number.prototype.mul = function  (ARG)  {    return accmul (arg, this);}; 

Floating-point number division:

/**  **  division function, which is used to get the exact division result  **  Description: The division result of JavaScript will be error, it will be more obvious when the two floating-point numbers divide. This function returns a more accurate division result.  **  Call: Accdiv (ARG1,ARG2)  **  return value: Arg1 divided by arg2 exact result  **/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);     }}//adds a Div method to the number type, More convenient to call. number.prototype.div = function  (ARG)  {    return accdiv (this,  ARG);};


The following information is from: http://madscript.com/javascript/javscript-float-number-compute-problem/

Analysis

JavaScript has only one numeric type number, and all the numbers in JavaScript are represented in the IEEE-754 standard format. The accuracy of floating-point numbers is not specific to JavaScript, because some decimals are binary representation of the number of bits that are infinite:

Decimal binary 0.1 0.0001 1001 1001 1001 ... 0.2 0.0011 0011 0011 0011 ... 0.3 0.0100 1100 1100 1100 ... 0.4 0.0110 0110 0110 0110 ... 0.5 0.10.6 0.1001 1001 1001 1001 ...

So for example, 1.1, its program actually can not really represent ' 1.1 ', and can only achieve a certain degree of accuracy, which is unavoidable loss of precision:

1.09999999999999999

The problem in JavaScript is even more complicated, and here are just a few things to test in chrome:

Input Output 1.0-0.9 = = 0.1 false1.0-0.8 = 0.2 false1.0-0.7 = 0.3 false1.0-0.6 = 0.4 true1.0-0.5 = = 0.5 true1.0-0.4 = = 0.6 true1.0-0.3 = = 0.7 true1.0-0.2 = 0.8 true1.0-0.1 = 0.9 True

The most popular method at present is to reduce the precision of calculation results before judging the result of floating-point operation, because the process of precision reduction will always be rounded automatically .

(1.0-0.9). toFixed (digits)//toFixed () The accuracy parameter must be between 0 and 20 parsefloat ((1.0-0.9). toFixed (10)) = = 0.1 The result is trueparsefloat ((1.0-0.8). toFixed (10)) = = = 0.2//result is trueparsefloat ((1.0-0.7). toFixed (10)) = = 0.3//Result TR Ueparsefloat ((11.0-11.8). toFixed (10)) = = = 0.8//result is true

line encapsulation of the above ideas

Use the IsEqual tool method to determine if the values are equal function isequal (number1, number2, digits) {digits = digits = undefined? 10:digits;//default accuracy is 1 0 return number1.tofixed (digits) = = = Number2.tofixed (digits);}  IsEqual (1.0-0.7, 0.3); Return true//native extension mode, prefer object-oriented style Number.prototype.isEqual = function (number, digits) {digits = digits = undefined? 10 : digits; The default accuracy is ten return this.tofixed (digits) = = = Number.tofixed (digits);} (1.0-0.7). IsEqual (0.3); return True


JavaScript floating-point arithmetic and comparison code collection and collation

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.