How to solve floating point in Javascript fractional Multiplication

Source: Internet
Author: User

A floating point error occurs during the multiplication of decimals in the (www.bkjia.com) Tutorial JS. You can test it as follows:

Reference content is as follows:
<Script>
Alert (11*22.9)
</Script>

The result is 251.89999999999998 instead of 251.9.

This problem may be a headache for many people. How can this problem be solved? A solution is provided here. The general idea of solving the problem is to first enlarge the factor into an integer and then divide it by the corresponding multiples to get the correct result.

Reference content is as follows:
<Script defer>
Number. prototype. rate = function (){
Var oStr = this. toString ();
If (oStr. indexOf (".") =-1)
Return 1;
Else
Return Math. pow (10, parseInt (oStr. length-oStr.indexOf (".")-1 ));
}

Function tran (){
Args = tran. arguments;
Var temp = 1;
For (I = 0; I <args. length; I ++)
Temp * = args [I] * args [I]. rate ();
For (I = 0; I <args. length; I ++)
Temp/= args [I]. rate ();
Return temp
}

Alert (tran (11, 22.9 ));

</Script>

This solution is troublesome, but it gives you a general idea about the actual process of solving this problem.

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.