How to use Decimals

TMT uses Decimals almost everywhere a numeric value is needed. They are different from normal Numbers in that they can go much, much higher, but are objects instead of a primitive. That means handling them is a little more complicated than Numbers. Fortunately, this guide will help.

Creating Decimals

Being an object, Decimals need to be created via a constructor. Those are lines of code that “construct” the object based on data you give it. Here’s an example of creating a Decimal with value zero:

new Decimal(0)

You can replace the 0 with any other valid Number value and it’ll also work. However, since Decimals can go above the highest Number value, you’ll also want to be aware of this constructor:

new Decimal("1e1000")

This one takes a string representation of a number, and you can input numbers greater than 1e308 this way.

Modifying Decimals

Decimals do not work with math operators! You cannot use +, -, /, or * with Decimals! Doing so will convert the Decimal to a Number and you’ll start getting tons of errors!

Instead, Decimals have a ton of functions that perform math operations on them - even more than javascript Numbers have! The basic ones are stuff like add, sub, times, sqrt, etc. There’s a lot of these, and unfortunately there isn’t a good list of all of them, but if you create a Decimal in your browser’s console you can use autocomplete or just print out the object to see a list of all of them.

There’s another important caveat, though! None of these functions actually modify the Decimal. They return the calculated value. That means if you want to add 1 to a Decimal, for example player.points, you have to do this:

player.points = player.points.add(1)

There are several synonyms for math operations, like .plus instead of .add, that might help you remember it’s returning a new value rather than modifying it’s current value. Forgetting this is a very common mistake, so don’t beat yourself up for making it. Just know it’s way better this way, once you start getting into complicated formulas.

Displaying Decimals

By default, printing a Decimal in HTML will include a lot of precision you may not need. There are several functions you can call to get the number in specific formats, like toExponential or toFixed, but in TMT there are also a couple utility functions that produce nice-looking strings for a variety of different Decimal values. Typically you’ll use either format or formatWhole, depending on whether or not you want to show decimal places on small values.