Skip to content
All library documents

Reducing JavaScript Decimal Errors with Scaled Integer Arithmetic

Article FMZ digest · Author: 善

Summary

The article explains why ordinary JavaScript arithmetic can produce small errors with decimal values: many decimal fractions cannot be represented exactly in binary floating-point. Such discrepancies can affect calculations and comparisons in trading logic, including price adjustments near an exchange’s minimum tick size. It illustrates the issue with subtraction and multiplication examples, then presents helper methods for addition, subtraction, multiplication, and division.

The proposed approach counts decimal places, scales operands by powers of ten so they can be handled as integers, performs the operation, and rescales the result. The article demonstrates the helpers on simple values and shows their intended use when adjusting an order price. This technique can reduce common decimal representation artifacts, but the examples do not address every numerical edge case. Scaling can itself exceed JavaScript’s safe integer range, and the string-based decimal counting may need extra care for scientific notation or unusual inputs. The helper should therefore be checked against the precision and value ranges of a specific trading application.

Key ideas

  • Binary floating-point cannot represent every decimal fraction exactly, which can introduce small calculation errors.
  • Scaling decimal operands to integers before arithmetic can reduce common representation artifacts.
  • The sample helper applies scaling and rescaling to addition, subtraction, multiplication, and division.
  • Price precision errors can affect order calculations and trading logic near tick increments.
  • The approach has limits, including safe integer bounds and inputs such as scientific notation.

Tags

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.