The accuracy of JavaScript parsefloat () functions is inconsistent.

Source: Internet
Author: User

The parsefloat () function parses a string and returns a floating point number.

Its syntax is: parsefloat (string );

Note: Only the first digit in the string is returned. spaces at the beginning and end are allowed.

Tip: if the first character of a string cannot be converted to a number, parsefloat () returns Nan. If you only want to parse the integer, use the parseint () method.

Example:

<script type="text/javascript"> document.write(parseFloat("10")) ; document.write(parseFloat("10.00")) ; document.write(parseFloat("10.33")) ; document.write(parseFloat("34 45 66")) ; document.write(parseFloat(" 60 ")) ; document.write(parseFloat("40 years")); document.write(parseFloat("He was 40")); </script>

Result:

 10 10 10.33 34 60 40 NaN

The above is an introduction to the parsefloat () function.

The following is a simple example of the problem:

Example: var num = parsefloat ("234432.9")-parsefloat "0.2"); alert (Num); Result: 234432.69999999998

Obviously, this result is not the one we want.

I don't know why this problem occurs. However, I have solved this problem by relying on DU Niang, so I will share the solution with you first!

First: Rounding math. Round (parsefloat ("234432.9")-parsefloat "0.2 "));
Second: retain a few decimal places
Num. tofixed (2); N in tofixed (n) indicates the number of reserved bits

Third: expand a certain number of times and narrow down the result.
VaR num1 = parsefloat ("234432.9") * 1000000000000;
VaR num2 = parsefloat ("0.2") * 1000000000000;
VaR num3 = (num1-num2)/1000000000000;
Result 234432.7

The first two practices are not recommended. There is no doubt that the first two practices will reduce the accuracy value! Therefore, the third type is recommended.

 

 

 

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.