orange psychedelic abstract mesh

Rounding Errors in TypeScript

Rounding Errors in TypeScript: Learn about the differences between `Number(props.tuzis).toFixed(0)` and `parseInt(props.tuzis)` for converting decimal strings to integers.

April 6, 2023· 2 min read
135 score

Tuzis (2Zs) are simple database credits that let you do things on free2z like store files, make AI prompts, subscribe to creators. They are implemented simply in Django:

    tuzis = models.DecimalField(        # You get 33 for creating an account        default=33, max_digits=17, decimal_places=3,        help_text="Creator's usable 2Z credits",        validators=[MinValueValidator(0)],    )

This is generally a good way to store quantities representing money because it is precise - not a floating point number. In fact, with the 2Z representing a digital wildcat penny, perhaps we don't even need the decimal places, an integer might have been better. A decimal on the wire translates to a precise quantity that is represented by a string - not a floating point number. "33.333" is exactly that.

Decimal -> string -> frontend -> ?

On the frontend we want to only show whole numbers (2$\mathbb{Z}$, afterall). So, we sort of want to throw away the digits after the decimal place. 2 choices for turning these decimal strings into integer-looking numbers/strings:

  • Number(props.tuzis).toFixed(0)
  • parseInt(props.tuzis)

These are different.

In TypeScript, which is a typed superset of JavaScript, the differences between Number(props.tuzis).toFixed(0) and parseInt(props.tuzis) are as follows:

  1. Number(props.tuzis).toFixed(0):

    This code snippet does the following:
    a. Converts props.tuzis to a Number type.
    b. Rounds the number to a fixed decimal place (0 decimal places in this case).
    c. Returns the result as a string.

    For example, if props.tuzis = 12.34, the result would be the string '12'.

  2. parseInt(props.tuzis):

    This code snippet does the following:
    a. Parses a string argument props.tuzis and returns an integer of the specified radix (base). The default radix is 10, which means it will return a decimal integer.
    b. If props.tuzis is a floating-point number or a string containing a floating-point number, parseInt() will truncate the decimal part and return the integer part.

    For example, if props.tuzis = '12.34', the result would be the integer 12.

In summary, the main differences are:

  • Number(props.tuzis).toFixed(0) returns a string, while parseInt(props.tuzis) returns an integer.
  • Number(props.tuzis).toFixed(0) rounds the number to the nearest integer, while parseInt(props.tuzis) truncates the decimal part.
  • parseInt(props.tuzis) expects a string input, while Number(props.tuzis) can work with both strings and numbers.

Related Articles