js precise calculation

js precise calculation
var numA = 0.1; 
var numB = 0.2; 
alert( numA + numB );

0.1 + 0.2 = 0.30000000000000004.
Computational precision error issues (related to binary).

For the four arithmetic operations of floating-point numbers, almost all programming languages ​​will have similar precision error problems, but in languages ​​such as C++/C#/Java, methods have been encapsulated to avoid precision problems. JavaScript is a weakly typed language, and from the design concept, there is no strict data type for floating-point numbers, so the problem of precision error is particularly prominent.

Let's convert 0.1 and 0.2 to binary:

0.1 => 0.0001 1001 1001 1001… (infinite loop)

0.2 => 0.0011 0011 0011 0011… (infinite loop)

The decimal part of a double-precision floating-point number supports up to 52 bits, so after adding the two together, we get a string of 0.0100110011001100110011001100110011001100110011001100110011001100, which is a binary number truncated due to the decimal limit of the floating-point number. At this time, when we convert it to decimal, it becomes 0.30000000000000004.

How to solve it?

First, multiply the number by a power of 10 and remove the decimal places to get an integer that can be converted to binary, and then restore it after calculation.

/** 
 ** Division function, used to get accurate division results** Note: JavaScript's division results will have errors, which will be more obvious when dividing two floating-point numbers. This function returns a more accurate 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) * Math.pow(10, t2 - t1);
    }
}

/**
 ** Addition function, used to get accurate addition results** Note: JavaScript addition results will have errors, which will be more obvious when adding two floating point numbers. This function returns a more accurate addition result.
 ** Call: accAdd(arg1,arg2)
 ** Return value: the exact result of arg1 plus arg2 **/

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 = 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;
}

/**
 ** Multiplication function, used to get accurate multiplication results** Note: JavaScript's multiplication results will have errors, which will be more obvious when multiplying two floating-point numbers. 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);
}

The above is the detailed content of js precise calculation. For more information about js precise calculation, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • js accurate countdown function sharing
  • Super accurate javascript method to verify ID number
  • js drag and drop table to realize content calculation
  • js implements a simple calculator
  • JS implementation of Apple calculator
  • JavaScript simulation calculator
  • JavaScript to achieve simple calculator function
  • How to calculate the number of lines of text in JavaScript
  • JavaScript classic case simple calculator

<<:  File backup solution between servers, how to automatically back up server files to another server?

>>:  Installation tutorial of MySQL 5.1 and 5.7 under Linux

Recommend

How to set mysql to case insensitive

mysql set to case insensitive Windows Go to the d...

Detailed explanation of MySQL index selection and optimization

Table of contents Index Model B+Tree Index select...

Example of how to check the capacity of MySQL database table

This article introduces the command statements fo...

How to use libudev in Linux to get USB device VID and PID

In this article, we will use the libudev library ...

Summary of English names of Chinese fonts

When using the font-family property in CSS to ref...

MySQL cross-table query and cross-table update

Friends who have some basic knowledge of SQL must...

Viewing and analyzing MySQL execution status

When you feel that there is a problem with MySQL ...

Detailed explanation of the problem of configuring servlet url-pattern in tomcat

When configuring web.xml for tomcat, servlet is a...

Mysql | Detailed explanation of fuzzy query using wildcards (like,%,_)

Wildcard categories: %Percent wildcard: indicates...

HTML table markup tutorial (14): table header

<br />In HTML language, you can automaticall...

js implements single click to modify the table

Pure js implements a single-click editable table ...

How to configure multiple projects with the same domain name in Nginx

There are two ways to configure multiple projects...

Detailed tutorial on building Gitlab server on CentOS8.1

There is no need to say much about the difference...

Basic JSON Operation Guide in MySQL 5.7

Preface Because of project needs, the storage fie...