floating-point-precision-in-javascript

If you have ever engaged with floating-point values in JavaScript, you may have encountered perplexing outcomes on occasion; the sum of 0.1 and 0.2 yields 0.30000000000000004, rather than precisely 0.3. This surprising behavior arises because JavaScript adheres to the IEEE 754 standard for number representation, which can lead to minor precision discrepancies in floating-point value computations. In this post, you will discover the reasons behind these discrepancies and learn how to manage them effectively.

Contents:

Frequent Problems With Floating-Point Number Precision

JavaScript represents numerical values as 64-bit floating-point values or IEEE 754 format. Certain decimal numbers such as 0.1 and 0.2 cannot be precisely represented in binary. Consequently, operations involving these floating-point values can lead to slight inaccuracies in the outcomes. Below are a few common challenges related to floating-point number precision:

Problem 1: Unforeseen Outcomes

The sum of two floating-point values like 0.1 and 0.2 does not equate to 0.3. Instead of the expected value 0.3, you will receive 0.30000000000000004.

Problem 2: Rounding Issues

When performing multiplication and division with floating-point values , accurate results are not guaranteed consistently.

Illustration:

Javascript

Code Copied!

var isMobile = window.innerWidth “);

editor70929.setValue(decodedContent); // Set the default text editor70929.clearSelection();

editor70929.setOptions({ maxLines: Infinity });

function decodeHTML70929(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard70929() { const code = editor70929.getValue(); // Get code from the editor navigator.clipboard.writeText(code).then(() => { // alert(“Code copied to clipboard!”);

jQuery(“.maineditor70929 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor70929 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode70929() {

var code = editor70929.getSession().getValue();

jQuery(“#runBtn70929 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”,

data: { language: “js”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output70929”).html(“

"+data+"");
									jQuery(".maineditor70929 .code-editor-output").show();
									jQuery("#runBtn70929 i.run-code").hide();

} })

}

function closeoutput70929() { var code = editor70929.getSession().getValue(); jQuery(".maineditor70929 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn70929").addEventListener("click", copyCodeToClipboard70929); document.getElementById("runBtn70929").addEventListener("click", runCode70929); document.getElementById("closeoutputBtn70929").addEventListener("click", closeoutput70929);

Result:

Rounding Issues

Clarification: A prevalent problem when utilizing floating-point values in computations is that whenever they are applied in multiplications and divisions, they may yield inaccurate results. For instance, console.log(1.007 * 100) could display the outcome as100.69999999999999, not 100.70.

Ways to Manage Floating-Point Precision in JavaScript

Here are several techniques to define the precision of floating-point numbers in JavaScript:

Technique 1: Utilizing toFixed()

The toFixed() function offers one of the most straightforward approaches to specify the precision of floating-point values in JavaScript. The toFixed(n) function adjusts a number to n decimal places and returns it as a string.

Example:

JavaScript

Code Copied!

var isMobile = window.innerWidth { jQuery(".maineditor11255 .copymessage").show(); setTimeout(function() { jQuery(".maineditor11255 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode11255() { var code = editor11255.getSession().getValue();

jQuery("#runBtn11255 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "js", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output11255").html("

"+data+"");
            jQuery(".maineditor11255 .code-editor-output").show();
            jQuery("#runBtn11255 i.run-code").hide();	
        }
    });
}

function closeoutput11255() { jQuery(".maineditor11255 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn11255").addEventListener("click", copyCodeToClipboard11255); document.getElementById("runBtn11255").addEventListener("click", runCode11255); document.getElementById("closeoutputBtn11255").addEventListener("click", closeoutput11255);

Output:

Using toFixed()

Clarification: In this illustration, the toFixed(1) method is employed to display a result with a precision of up to 1 decimal. You can modify this value as per your requirements.

Technique 2: Utilizing toPrecision()

The toPrecision(n) function adjusts a number to n significant digits. This is helpful to regulate the entire count of digits instead of merely the decimals.

Example:

JavaScript

Code Copied!

var isMobile = window.innerWidth { jQuery(".maineditor34328 .copymessage").show(); setTimeout(function() { jQuery(".maineditor34328 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }```javascript function executeCode34328() {

var script = editor34328.getSession().getValue();

jQuery("#executeBtn34328 i.run-script").show(); jQuery(".output-section").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post",

data: { language: "js", script: script, command_line_arguments: "", variable_names: "", action:"compilerajax" }, success: function(result) { var resultArray = result.split("~"); var outputData = resultArray[1];

jQuery(".output34328").html("

"+outputData+"");
									jQuery(".maineditor34328 .code-editor-output").show();
									jQuery("#executeBtn34328 i.run-script").hide();

} })

}

function hideOutput34328() { var script = editor34328.getSession().getValue(); jQuery(".maineditor34328 .code-editor-output").hide(); }

// Link event listeners to the buttons document.getElementById("copyBtn34328").addEventListener("click", copyScriptToClipboard34328); document.getElementById("executeBtn34328").addEventListener("click", executeCode34328); document.getElementById("hideoutputBtn34328").addEventListener("click", hideOutput34328);

Output:

Using toPrecision()

Explanation: In this illustration, the toPrecision() function is utilized to determine the precision value for floating-point values. Here, the .toPrecision(4) displays the value with a length of 4.

Method 3: Multiplication and Division Technique

A rational method to regulate the precision for floating-point values involves using both multiplication and division when performing calculations involving floating-point values.

Example:

Javascript

Code Copied!

var mobileView = window.innerWidth ");

editor33198.setValue(decodedJavascript); // Set the initial text editor33198.clearSelection();

editor33198.setOptions({ maxLines: Infinity });

function decodeHTML33198(input) { var documentElement = new DOMParser().parseFromString(input, "text/html"); return documentElement.documentElement.textContent; }

// Function to copy script to clipboard function copyScriptToClipboard33198() { const code = editor33198.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code copied to clipboard!");

jQuery(".maineditor33198 .copymessage").show(); setTimeout(function() { jQuery(".maineditor33198 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error while copying code: ", err); }); }

function executeCode33198() {

var script = editor33198.getSession().getValue();

jQuery("#executeBtn33198 i.run-script").show(); jQuery(".output-section").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post",

data: { language: "js", script: script, command_line_arguments: "", variable_names: "", action:"compilerajax" }, success: function(result) { var resultArray = result.split("~"); var outputData = resultArray[1];

jQuery(".output33198").html("

"+outputData+"");
									jQuery(".maineditor33198 .code-editor-output").show();
									jQuery("#executeBtn33198 i.run-script").hide();

} })

}

function hideOutput33198() { var script = editor33198.getSession().getValue(); jQuery(".maineditor33198 .code-editor-output").hide(); }

// Link event listeners to the buttons document.getElementById("copyBtn33198").addEventListener("click", copyScriptToClipboard33198); document.getElementById("executeBtn33198").addEventListener("click", executeCode33198); document.getElementById("hideoutputBtn33198").addEventListener("click", hideOutput33198);

Output:

Multiplication and Division Technique

Explanation: In this demonstration, Math.round((0.1 + 0.2) * 100) computes the result as 30, and when 30 is divided by 100, it presents the result as 0.3.

Method 4: Utilizing an External Library

At times, you may need the result with strict accuracy. Thus, external libraries like Big.js, Decimal.js, and Math.js, which cater to high-precision computations, can be beneficial.

Example:

Javascript

Code Copied!

``````html
class="code-editor-output-wrap output811">

var isMobile = window.innerWidth “);

editor811.setValue(decodedContent); // Set the initial text editor811.clearSelection();

editor811.setOptions({ maxLines: Infinity });

function decodeHTML811(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Function to duplicate code to clipboard function copyCodeToClipboard811() { const code = editor811.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { // alert(“Code duplicated to clipboard!”);

jQuery(“.maineditor811 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor811 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error duplicating code: “, err); }); }

function runCode811() {

var code = editor811.getSession().getValue();

jQuery(“#runBtn811 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”,

data: { language: “js”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output811”).html(“

"+data+"");
									jQuery(".maineditor811 .code-editor-output").show();
									jQuery("#runBtn811 i.run-code").hide();

} })

}

function closeoutput811() { var code = editor811.getSession().getValue(); jQuery(".maineditor811 .code-editor-output").hide(); }

// Attach event listeners to the buttons document.getElementById("copyBtn811").addEventListener("click", copyCodeToClipboard811); document.getElementById("runBtn811").addEventListener("click", runCode811); document.getElementById("closeoutputBtn811").addEventListener("click", closeoutput811);

Result:

Utilizing an External Library

Clarification: Utilizing an external library such as Big.js proves to be extremely beneficial when conducting high-accuracy computations.

Optimal Methods

  • Always round numbers prior to applying them in calculations.
  • Employ toFixed() or toPrecision() if you wish to display results solely.
  • For monetary calculations, contemplate using external libraries such as Big.js or Decimal.js

Final Thoughts

Floating-point number precision challenges are prevalent in JavaScript due to its application of IEEE 754 floating-point arithmetic. Nonetheless, by comprehending the problems and the techniques to resolve this challenge, such as toFixed(), toPrecision(), and the Big.js library, you can effectively handle floating-point number precision in your applications.

Guidelines for Establishing Floating Point Number Precision in JavaScript – FAQs

Q1. Why is 0.1 + 0.2 !== 0.3 in JavaScript?

JavaScript encodes numbers utilizing the IEEE 754 floating-point standard. Values such as 0.1 and 0.2 cannot be faithfully represented in binary, resulting in minimal rounding discrepancies.

Q2. How to accurately compare floating-point numbers?

To compare floating-point numbers in JavaScript, utilize Number.EPSILON. It is the preferred method for verifying the equality of floating-point values.

Q3. Which library is best suited for high-precision calculations?

For executing high-precision calculations, libraries like Big.js, Decimal.js, and Math.js are employed. These tools are adept at conducting arithmetic operations with enhanced precision.

Q4. How can you restrict a float to 2 decimal places in JavaScript?

You may utilize toFixed(2) to constrain floating-point numbers to 2 decimal places in JavaScript.

Q5. What is the precision of a number in JavaScript?

JavaScript employs double-precision floating-point values (64-bit IEEE 754). The maximum secure integer is Number.MAX_SAFE_INTEGER (253 – 1), and the smallest difference between two values is Number.EPSILON (~2.22e-16).

The article Floating Point Precision in JavaScript originally appeared on Intellipaat Blog.

“`


Leave a Reply

Your email address will not be published. Required fields are marked *

Share This