JS decimal to calculate the number of decimal points after the decimal point realization method _javascript Tips

Source: Internet
Author: User

First write a demo replay problem, I am using a JS online test environment [open]

Overwrite Displaynum () function

function Displaynum () {var = 22.77;alert (num + 10);}

Clicking on the Show button results in 32.769999999996 occurrences of N-decimals.

Not all numbers are going to happen, except for 22.99, 2.777, as if these numbers are nothing special.

Looked up some information, one is the JS floating-point calculation of the bug, and the computer eventually converted into binary calculation, but why not all decimal will have this phenomenon, at present I am not clear, there is time to further study.

Now there are two solutions, the first is to use the JS. ToFixed (n) method, directly to get n decimal places, I think this method in the data precision will have some problems. It can be used if the data accuracy requirements are not high. The second way is to write their own JS method of operation.

The following is a custom addition function, which is added by using this method to avoid the above problem.

function Addnum (num1,num2) {var sq1,sq2,m;try{sq1=num1.tostring (). Split (".") [1].length;} catch (e) {sq1=0;} Try{sq2=num2.tostring (). Split (".") [1].length;} catch (e) {sq2=0;} M=math.pow (10,math.max (SQ1,SQ2)); return (NUM1 * m + num2 * m)/m;}

Of course, simplicity can also be written as alert (NUM * 3 + 10 * 3)/3); This also does not appear n many decimal places.

Alert ((NUM * 3 + 10 * 3)/3); With alert (num + 10); There is a difference between the two ways in which computers are converted to binary operations at the bottom, and perhaps that's why the problem arises.

The above JS decimal point to calculate the number of decimal points after the realization of the method is small to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.