How to manage Javascript rounding errors

Description

The Loftware LabelClosed A label is a design area on the computer screen where a label format is created or edited. Manager (LLM) has a powerful tool in the form of the Script Data SourceClosed Where data is extracted to produce labels. Loftware Label Manager provides a variety of data sources, including the keyboard, a database, serial number, a formula, via the UCC or UPN Wizard. For RFID labels and tags, data can come from the Keyboard data source or by configuring data blocks using the Block Configuration data source.. JavaScript allows for complex logic to be added to labels but in some cases the way JavaScript handles mathematical operations can cause issues. Unlike other script and programming languages JavaScript does not allow for different numeric types (i.e. integer, float, long, short, byte, double, etc), JavaScript has "Number". In some cases where precision is important for comparisons math operations will return an un expected value (i.e. 1+1=1.9999999999999999);

Example:

Variables have been replaced with numbers to illustrate the issue.

First computation:

var ratio = (78 - 42) / (78 - 42); // ratio=1

var center = 2.27 + ((5.15 - 2.27) * ratio) + .08; // center = 5.23

Second computation:

var upper_boundary = 1.39 + 3.84; // upperboundary=5.23

Actual returned values:

The center value failed a check that it was less than or equal (<=) to the upper_boundary.

How to manage JavaScript rounding errors.

To manage the rounding errors of this nature you need to implement the following code change. This example would be valid for a 2 decimal point accuracy.

(Math.round((value1 + value2)*100))/100

This first multiplies the result by 100

5.2299999999999995*100 = 522.99999999999995

Math.round rounds the target value to the closest Integer value

Math.round(522.99999999999995) = 523

Finally divide the resulting value by 100

523/100 = 5.23

To implement for 3 decimal places change 100 to 1000, or if you want no decimal places you can simply use the Math.round without the multiplication or division.