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.