{
  "id": "scruss/micropython-decimal-number",
  "name": "micropython-decimal-number",
  "prettyName": "micropython-decimal-number",
  "description": "Micropython Decimal Number Module",
  "version": "",
  "author": "scruss",
  "license": "MIT",
  "tags": [],
  "status": "VALID",
  "official": false,
  "source": "https://github.com/scruss/micropython-decimal-number",
  "updatedAt": "2025-10-23T07:01:05.683Z",
  "page": "https://checkmim.com/packages/scruss+micropython-decimal-number",
  "createdAt": "2025-10-22T09:36:35.088Z",
  "submittedBy": "scruss",
  "install": {
    "mpremote": "mpremote mip install github:scruss/micropython-decimal-number",
    "mip": "import mip; mip.install(\"github:scruss/micropython-decimal-number\")"
  },
  "readme": "# Decimal floating point arithmetic for micropython\nThis Python module for [*micropython*](https://micropython.org/) and [*CircuitPython*](https://circuitpython.org/) provides support for decimal floating point arithmetic. It tries to overcome the limitations of single precision float numbers (32-bit) and provides a solution when double precision float numbers (64 bit) are not enough.\n\nThe Python Standard Library contains the wonderful module [*decimal*](https://docs.python.org/3/library/decimal.html), but it has not been ported to *micropython*. This module provides a small, but valuable, part of the functionality of *decimal*.\n\n## Introduction\n\nThe module **mpy_decimal** defines the class **DecimalNumber** that contains all the functionality for decimal floating point arithmetic. A **DecimalNumber** can be of arbitrary precision. Internally, it is composed of an *int* that contains all the digits of the **DecimalNumber**, an *int* equal to the number of decimal places and a *bool* that determines whether the **DecimalNumber** is positive or negative. Example:\n\n    DecimalNumber: -12345678901.23456789\n        number   = 1234567890123456789\n        decimals = 8\n        positive = False\n\nThe precision of **DecimalNumber** is mainly limited by available memory and procesing power. **DecimalNumber** uses the concept **scale**, which is the number of decimal places that the class uses for its numbers and operations. The concept is similar to the use of 'scale' in the calculator and language [*bc*](https://www.gnu.org/software/bc/manual/html_mono/bc.html).  The default value for **scale** is 16. It is a global value of the class that can be changed at any time. For rounding, **DecimalNumber** uses [*round half to even*](https://en.wikipedia.org/wiki/Rounding#Round_half_to_even).\n\n## Performance ##\n\nAll the internal operations of **DecimalNumber** are done with integers (*int* built-in type of Python) and the number of decimals are adjusted according to the operation. It is fast, but not as fast as Python's *decimal* class because **DecimalNumber** is pure Python and *decimal* is written in C. The *test* folder contains the file \"*perf_decimal_number.py*\" that calculates the performance of **DecimalNumber** on the device where it runs. This is the output of that program executed on a [*Raspberry Pi Pico*](https://www.raspberrypi.org/products/raspberry-pi-pico/). Basic operations take about one millisecond with scale = 16:\n\n    +---------------------------------------------------------------+\n    |  SYSTEM INFORMATION                                           |\n    +---------------------------------------------------------------+\n    Implementation name:           micropython\n    Implementation version:        1.17.0\n    Implementation platform:       rp2\n    CPU frequency:                 125 Mhz\n\n    +---------------------------------------------------------------+\n    |  PERFORMANCE WITH SCALE = 16                                  |\n    +---------------------------------------------------------------+\n    Scale (max. decimals):         16\n    Iterations per test:           1000\n    Number 1:                      63107666423864.1503618336011148\n    Number 2:                      21513455188640.8462728528253754\n    Addition (n1 + n2):            1.564 ms\n    Subtraction (n1 - n2):         1.695 ms\n    Multiplication (n1 * n2):      0.988 ms\n    Division (n1 / n2):            1.184 ms\n    Square root abs(n1):           3.984 ms\n    Power: (pi/2) ** 15            9.799 ms\n    DecimalNumber from int:        0.378 ms\n    DecimalNumber from string:     3.685 ms\n    Iterations per test:           10\n    Sine: sin(0.54321)             85.80001 ms\n    Cosine: cos(0.54321)           86.7 ms\n    Tangent: tan(0.54321)          206.7 ms\n    Arcsine: asin(0.54321)         270.2 ms\n    Arccosine: acos(0.65432)       468.8 ms\n    Arctangent: atan(1.2345)       485.5 ms\n    Arctangent2: atan2(1.23, 2.34) 349.2 ms\n    Exponential: exp(12.345)       151.0 ms\n    Natural logarithm: ln(12.345)  152.0 ms\n\n    +---------------------------------------------------------------+\n    |  PERFORMANCE WITH SCALE = 50                                  |\n    +---------------------------------------------------------------+\n    Scale (max. decimals):         50\n    Iterations per test:           400\n    Number 1:                      1008440840554324243744283306032711702.13787157234850455642441824006520576852374144010113\n    Number 2:                      -603053031456028063831871487068.81514266625502376325215658564112814751837118860547\n    Addition (n1 + n2):            1.9575 ms\n    Subtraction (n1 - n2):         2.25 ms\n    Multiplication (n1 * n2):      1.4625 ms\n    Division (n1 / n2):            1.52 ms\n    Square root abs(n1):           12.455 ms\n    Power: (pi/2) ** 15            11.7425 ms\n    DecimalNumber from int:        0.385 ms\n    DecimalNumber from string:     10.055 ms\n    Iterations per test:           4\n    Sine: sin(0.54321)             186.25 ms\n    Cosine: cos(0.54321)           184.5 ms\n    Tangent: tan(0.54321)          398.75 ms\n    Arcsine: asin(0.54321)         831.25 ms\n    Arccosine: acos(0.65432)       1322.25 ms\n    Arctangent: atan(1.2345)       1377.75 ms\n    Arctangent2: atan2(1.23, 2.34) 893.4999 ms\n    Exponential: exp(12.345)       281.75 ms\n    Natural logarithm: ln(12.345)  281.75 ms\n\n    +---------------------------------------------------------------+\n    |  CALCULATING PI                                               |\n    +---------------------------------------------------------------+\n    Pi with 300 decimals:          5.862 s\n    3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141274\n\n## How to use\n\nTo test this module on a PC, you can start by importing the module:\n\n```python\nfrom mpy_decimal.mpy_decimal import *\n```\n\nFor testing on a Micropython board, you have probably copied the file 'mpy_decimal.py' to the board or a compiled version of it: 'mpy_decimal.mpy'. There is a guide that explains how to compile this module and how to copy it to a device at the end of this document. You can import the module with:\n\n```python\nfrom mpy_decimal import *\n```\n\nIf you need your code to run on both, a computer and a micropython board, you will probably need to run different code depending on the device. You can do it this way:\n\n```python\nimport sys\n\nif sys.implementation.name == \"cpython\":\n    # ... your imports or other code for CPython here ...\n\nif sys.implementation.name == \"micropython\":\n    # ... your imports or other code for Micropython here ...\n```\n\n(Note: 'sys' is standard Python and it has nothing to do with **DecimalNumber**)\n\n### Initialization ###\nA **DecimalNumber** with default value, equal to zero:\n\n\n```python\nn = DecimalNumber()\n```\n\nAn integer, for example, 748:\n\n```python\nn = DecimalNumber(748)\n```\n\nA decimal number, for example, 93402.5184:\n\n```python\nn = DecimalNumber(934025184, 4)\n```\n\nNotice that the first parameter is an integer with all the digits and the second one the number of decimals.\n\nThe same number can be created providing a string with the number:\n\n```python\nn = DecimalNumber(\"93402.5184\")\n```\n\n### Printing and formating ###\nNumbers can be printed using 'print()':\n\n```python\nprint(n)\n# Result: 93402.5184\n```\n\nThey can be converted to a string using 'str()':\n\n```python\nstr(n)\n```\n\n\nThe method **to_string_thousands()** of **DecimalNumber** returns a string with the number formatted with ',' as thousands separator. Decimals figures are not modified:\n\n```python\nprint(n.to_string_thousands())\n# Result: 93,402.5184\n```\n\nMicropython can be used to print information on displays with a limited number of characters. For example, on a 16x2 LCD (two lines of 16 characters). For these kind of cases exists the method **to_string_max_length()**. It limits the representation of the number to a maximum length of characters, including '.' and '-'. The minimum value is 8. If decimals cannot fit in, they are discarded. If the integer part of the number is bigger than the maximum length, the result is the string \"Overflow\". Some examples:\n\n```python\nn = DecimalNumber(\"123456789.012\")\n#                           ¹¹¹¹\n#                  ¹²³⁴⁵⁶⁷⁸⁹⁰¹²³ \n\nprint(n.to_string_max_length(12))\n# Result: 123456789.01\n\nprint(n.to_string_max_length(11))\n# Result: 123456789\n\nprint(n.to_string_max_length(8))\n# Result: Overflow\n```\n\n### Modifying the **scale** of **DecimalNumber** ###\n\n**scale** is a global value of the class **DecimalNumber** that stores the number of decimals that the class uses for its numbers an operations. The default value is 16. **DecimalNumber.get_scale()** returns the current **scale** and the method **DecimalNumber.set_scale()** sets **scale**:\n\n```python\ncurrent_scale = DecimalNumber.get_scale()   # Gets the scale\nDecimalNumber.set_scale(100)                # Sets the scale to 100\n\n    # ... Code to calculate something using the new scale\n\nDecimalNumber.set_scale(current_scale)      # Back to the previous scale \n```\n\n### Operations ###\n\n**Basic operations**\n\nThe basic operations (addition, subtraction, multiplication and division) allow to mix **DecimalNumber** objects and *int* objects. The result is always a **DecimalNumber**. Examples:\n\n```python\na = DecimalNumber(\"7.3329\")\nb = DecimalNumber(\"157.82\")\n\n# Addition\nc = a + b       # DecimalNumber + DecimalNumber\nc = a + 5       # DecimalNumber + int\nc = 5 + a       # int + DecimalNumber\na += b          # DecimalNumber + DecimalNumber\na += 3          # DecimalNumber + int\n\n# Subtraction\nc = a - b       # DecimalNumber - DecimalNumber\nc = a - 5       # DecimalNumber - int\nc = 5 - a       # int - DecimalNumber\na -= b          # DecimalNumber - DecimalNumber\na -= 3          # DecimalNumber - int\n\n# Multiplication\nc = a * b       # DecimalNumber * DecimalNumber\nc = a * 5       # DecimalNumber * int\nc = 5 * a       # int * DecimalNumber\na *= b          # DecimalNumber * DecimalNumber\na *= 3          # DecimalNumber * int\n\n# Division\nc = a / b       # DecimalNumber / DecimalNumber\nc = a / 5       # DecimalNumber / int\nc = 5 / a       # int / DecimalNumber\na /= b          # DecimalNumber / DecimalNumber\na /= 3          # DecimalNumber / int\n```\n**Exponentiation**\n\nThe operands for exponentition are a **DecimalNumber**, the base, and an *int*, the exponent. It calculates the base raised to the exponent. Examples:\n\n```python\na = DecimalNumber(\"1.01234567\")\nb = a ** 15     # a¹⁵ = 1.2020774344056969\n\n# 11th Mersenne prime = 2¹⁰⁷ - 1 = 162259276829213363391578010288127\nm11 = DecimalNumber(2) ** 107 - 1\n```\n\n**Square root**\n\nIt calculates the square root of a positive **DecimalNumber**. For negative numbers, a **DecimalNumberExceptionMathDomainError** exception is raised. Example:\n\n```python\na = DecimalNumber(\"620433.785\")\nb = a.square_root()\nprint(b)        # Result: 787.6761929879561873\n```\n\n**Absolute**\n\nIt returns the absolute value of a **DecimalNumber**. Examples:\n\n```python\na = DecimalNumber(\"12.762\")\nb = DecimalNumber(\"-12.762\")\nprint(abs(a))   # Result: 12.762\nprint(abs(b))   # Result: 12.762\n```\n\n**Unary - operator**\n\nGiven a **DecimalNumber** n, it returns -n. Example:\n\n```python\na = DecimalNumber(\"12.762\")\nb = DecimalNumber(\"-12.762\")\nprint(-a)   # Result: -12.762\nprint(-b)   # Result: 12.762\n```\n\n**Unary + operator**\n\nGiven a **DecimalNumber** n, it returns +n. This can give the idea that it does nothing to the number n. That is true if the number of decimals of n is less or equal than the **scale** of **DecimalNumber**. If it is not, if the number of decimals of n is greater than **scale**, the decimals of n are reduced and rounded to match **scale**.\n\nThis operator can be useful to adjust the **scale** of a number to the **scale** of **DecimalNumber** after changing the **scale** with the method **DecimalNumber.set_scale()**. An example of this is a method that increases **scale** to obtain better accuracy in the calculation of a number x. Before returning from the method, it sets **scale** back to the value it had before entering the method and it returns +x instead of just x, adjusting the decimals of x to **scale**. Example:\n\n```python\na = DecimalNumber(2)\nDecimalNumber.set_scale(30)     # Sets the scale = 30\nr2 = a.square_root()            # Calculates the square root of 2 with 30 decimals\nprint(r2)                       # 1.414213562373095048801688724209\nDecimalNumber.set_scale(10)     # Sets the scale = 10\nprint(r2)                       # 1.414213562373095048801688724209\n                                # Changing the scale does not modify a number\n                                # unless an operation is made with it, like,\n                                # for example, the unary + operator:\nprint(+r2)                      # 1.4142135624\n```\n\n### Comparisons operators ###\n\nThese are the common comparison operators we all know: <, <=, ==, !=, >=, >.\n\nA **DecimalNumber** can be compared to other **DecimalNumber** or to an *int* number. Examples:\n\n```python\na = DecimalNumber(\"1.2\")\nb = DecimalNumber(\"8.3\")\nprint(a > b)    # False\nprint(b > a)    # True\nprint(a == b)   # False\nprint(a != b)   # True\nprint(a > 0)    # True\nprint(1 > b)    # False\n```\n\n### Other mathematical functions ###\n\n**exp()**: exponential function e<sup>x</sup>.\n\n**ln()**: natural logarithm (base e).\n\n**Trigonometric functions**:\n\n**sin()**: sine.\n\n**cos()**: cosine.\n\n**tan()**: tangent.\n\nThe argument of trigonometric functions sin(), cos() and tan() is an angle expressed in radians.\n\n**asin()**: arcsine.\n\n**acos()**: arccosine.\n\n**atan()**: arctangent.\n\n**atan2()**: 2-argument arctangent.\n\nThe functions asin(), acos(), atan() and atan2() return an angle in radians.\n\nExample:\n\n```python\nn = DecimalNumber(\"0.732\")\nn.exp()     # 2.0792349218188443\nn.ln()      # -0.3119747650208255\nn.sin()     # 0.6683586490759965\nn.cos()     # 0.7438391736157144\nn.tan()     # 0.8985257469396026\nn.asin()    # 0.821252884452186\nn.acos()    # 0.7495434423427106\nn.atan()    # 0.6318812315412357\nn2 = DecimalNumber(\"1.732\")\nDecimalNumber.atan(n, n2)   # 0.3998638956924461\n```\n\n### Other methods ###\n\n**to_int_truncate()** returns and *int* that contains the integer part of a **DecimalNumber** after truncating the decimals.\n\n**to_int_round()** returns and *int* that contains the integer part of a **DecimalNumber** after rounding it to zero decimals.\n\nExample:\n\n```python\na = DecimalNumber(\"623897401.877314\")\nprint(a.to_int_truncate())  # 623897401\nprint(a.to_int_round())     # 623897402\n```\n\n**clone()** returns a new **DecimalNumber** object as a clone of a **DecimalNumber**. Example:\n\n```python\na = DecimalNumber(\"657.31\")\nb = a.clone()\nprint(a == b)   # True: they are equal numbers.\nprint(a is b)   # False: they are different objects.\n```\n\n**copy_from()** copies into a **DecimalNumber** other **DecimalNumber** passed as a parameter. The reason for this method is that Python does not allow to overload the *assign* operator: '='. \"b = a\" would make b to point to object a, they would be the same object. We need a way to copy one into the other while remaining independent objects. Example:\n\n```python\na = DecimalNumber(\"657.31\")\nb = DecimalNumber(\"-1.9\")\nb = a\nprint(a, b)     # 657.31 657.31\nprint(a is b)   # True: they are the same object\n\n# Let's try again with 'copy_from()'\n\na = DecimalNumber(\"657.31\")\nb = DecimalNumber(\"-1.9\")\nb.copy_from(a)\nprint(a, b)     # 657.31 657.31\nprint(a is b)   # False: they are different objects.\n```\n\n**pi()** is a class method that returns the number PI with as many decimals as the **scale** of **DecimalNumber**. Example:\n\n```python\npi = DecimalNumber.pi()         # Default scale, equal to 16\nprint(DecimalNumber.pi())       # 3.1415926535897932\nDecimalNumber.set_scale(36)     # Set scale = 36\nprint(DecimalNumber.pi())       # 3.141592653589793238462643383279502884\n```\n\nPI is precalculated with 100 decimals and stored in the class. If **pi()** method is used with **scale** <= 100, PI is not calculated, but returned using the precalculated value. If **scale** is set to a value greater than 100, for example, 300, PI is calculated, stored in the class and returned. After that, the precalculated limit is 300 instead of 100, and any call to **pi()** with a **scale** <= 300 returns the value of PI from the precalculated value.\n\nTo calculate PI, this method uses the very fast algorithm present on the section [Recipes](https://docs.python.org/3/library/decimal.html#recipes) of the documentation for the module **decimal**, part of Python Standard Library.\n\n**e()** is a class method that returns the number e number, the base of natural logarithms, with as many decimals as the **scale** of **DecimalNumber**. Its value is precalculated and it functions in a similar way as pi(). Example:\n\n```python\ne = DecimalNumber.e()           # Default scale, equal to 16\nprint(DecimalNumber.pi())       # 2.7182818284590452\nDecimalNumber.set_scale(36)     # Set scale = 36\nprint(DecimalNumber.e())        # 2.718281828459045235360287471352662498\n```\n\n### Other considerations ###\n\n**DecimalNumber** class can operate mixing *int* numbers and **DecimalNumber** objects. *float* numbers were not considered because of their imprecision.\n\nTry this using CPython (on a PC):\n```python\nprint( (0.1 + 0.1 + 0.1) == 0.3 )   # False!!!\n```\n\nThere is nothing wrong with Python, it is the way *float* numbers work.\n\nTry this using Micropython (I have used a Raspberry Pi Pico):\n\n```python\n# Compares 10¹¹ * 10⁻² to 10⁹, which should be True\nprint( (1e11 * 1e-2) == 1e9 )       # False!!!\n```\n\n\n## Exceptions ##\n\nThis module defines four exceptions:\n\n* **DecimalNumberExceptionParseError**: a \n**DecimalNumber** can be initialize providing a string that contains a number. If the content of the string cannot be parsed as a correct number, this exception is raised.\n\n* **DecimalNumberExceptionBadInit**: this exception is raised when a negative number of decimals is provided when initializing a **DecimalNumber**.\n\n* **DecimalNumberExceptionMathDomainError**: this exception occurs when trying to calculate the square root of a negative number or atan2(0, 0).\n\n* **DecimalNumberExceptionDivisionByZeroError**: this is the division by zero exception.\n\n\n## Example ##\n\nThis example shows how to use **DecimalNumber** to solve quadratic equations.\n\n```python\nfrom mpy_decimal.mpy_decimal import *\n\n\ndef solve_quadratic_equation(a: DecimalNumber, b: DecimalNumber, c: DecimalNumber) -> Tuple[bool, DecimalNumber, DecimalNumber]:\n    \"\"\"It solves quadratic equations:\n    a * x² + b * x + c = 0\n    x₁ = (-b + sqrt(b*b - 4*a*c)) / (2*a)\n    x₂ = (-b - sqrt(b*b - 4*a*c)) / (2*a)\n    \"\"\"\n\n    # This is done by catching the Exception raised when calculating\n    # the square root of a negative number. It is instructive, but it\n    # can be avoided by simply checking if (b * b - 4 * a * c) is a\n    # negative number before calling square_root().\n    try:\n        r = (b * b - 4 * a * c).square_root()\n        x1 = (-b + r) / (2 * a)\n        x2 = (-b - r) / (2 * a)\n        return True, x1, x2\n    except DecimalNumberExceptionMathDomainError:\n        return False, None, None\n\n\ndef string_equation(a: DecimalNumber, b: DecimalNumber, c: DecimalNumber) -> str:\n    return \"{0}x² {1}x {2} = 0\".format(\n        a,\n        \"- \" + str(abs(b)) if b < 0 else '+ ' + str(b),\n        \"- \" + str(abs(c)) if c < 0 else '+ ' + str(c)\n    )\n\n\nlist_equations = [\n    (7, -5, -9),\n    (1, -3, 10),\n    (4, 25, 21),\n    (1, 3, -10)\n]\n\nprint(\"-\" * 50)\nfor e in list_equations:\n    a = DecimalNumber(e[0])\n    b = DecimalNumber(e[1])\n    c = DecimalNumber(e[2])\n    solution, x1, x2 = solve_quadratic_equation(a, b, c)\n    print(string_equation(a, b, c))\n    if solution:\n        print(\"   x₁ =\", x1)\n        print(\"   x₂ =\", x2)\n    else:\n        print(\"   The equation does not have a real solution.\")\n    print(\"-\" * 50)\n```\n\nThis is what the program prints:\n\n    --------------------------------------------------\n    7x² - 5x - 9 = 0\n       x1 = 1.545951212649517\n       x2 = -0.8316654983638027\n    --------------------------------------------------\n    1x² - 3x + 10 = 0\n       The equation does not have a real solution.\n    --------------------------------------------------\n    4x² + 25x + 21 = 0\n       x1 = -1\n       x2 = -5.25\n    --------------------------------------------------\n    1x² + 3x - 10 = 0\n       x₁ = 2\n       x₂ = -5\n    --------------------------------------------------\n\n\n## Using DecimalNumber on a Micropython board ##\n\nThis is not exactly part of this module, but someone might find it useful.\n\n**\".mpy\" files**: a micropython board can run \".py\" files directly. It compiles them before executing them, and that takes time. It is a good practice to copy to your micropython board a precompiled version, a \".mpy\" file.\n\nYou can compile the Python file \"mpy_decimal.py\", that contains all the functionality of **DecimalNumber**, before copying it to your micropython board:\n\n```shell\npython -m mpy_cross mpy_decimal.py\n```\n\nIt creates the file \"mpy_decimal.mpy\". You should have **mpy_cross** installed. More information at: [https://pypi.org/project/mpy-cross/](https://pypi.org/project/mpy-cross/)\n\nThe next step is copying the \".mpy\" file to your micropython board. You can copy python source code files with an editor, for example [**Thonny**](https://thonny.org/), but it does not copy (as of today) \".mpy\" files. The tool [**mpy-repl-tool[mount]**](https://mpy-repl-tool.readthedocs.io/en/latest/index.html) can help you connect your computer to your micropython board. It also allows to mount your board and use it as any other disk or memory unit of your computer.\n"
}