How to Fix Floating-Point Problems in JavaScript

How to Fix Floating-Point Problems in JavaScript thumbnail
Use JavaScript's rounding function to reduce floating-point errors.

JavaScript is a simple, efficient language that can add functionality and flair to a website. Before adding a script on a page to perform conversions or calculations, you need to be aware of a flaw in the way JavaScript handles floating-point numbers. Floating-point numbers, or floats, are numbers that contain decimal fractions. Due to JavaScript's method for storing these numbers, results of simple calculations can sometimes be surprising. Adding the numbers 0.01 and 0.06 with JavaScript gives a result of 0.069999. Fortunately, there is a simple way to resolve this problem.

Instructions

    • 1

      Assign a floating-point value to two variables using the assignment operator:

      FirstFloat = 0.01;
      SecondFloat = 0.06;

    • 2

      Multiply both values by 10,000 with the following statements:

      FirstFloat = FirstFloat * 10000;
      SecondFloat = SecondFloat * 10000;

    • 3

      Add both variables and assign the result to a third variable with this code:

      Result = FirstFloat + SecondFloat;

    • 4

      Divide the sum by 10,000 to find the correct answer with the following statement:

      Result=Result/10000;

    • 5

      Output the answer to the screen using the document.write function:

      document.write(result);

Tips & Warnings

  • Increase the accuracy of your results by increasing the multiplier and divisor. Changing both values to 100 yields two decimal places of accuracy. Each zero added to the end of the multiplier/divisor adds another decimal place of accuracy.

  • This method works on all arithmetic operations. Multiply each variable before performing the desired operation. Divide the answer before printing or using it in another calculation.

  • The multiplier and divisor in the rounding statement must always have equivalent values.

Related Searches:

References

Resources

  • Photo Credit Ablestock.com/AbleStock.com/Getty Images

Comments

Related Ads

Featured