Skip to content

Bug: nstr returns empty string for 0 with maxDecimals: 0 #9

Description

@schplitt

Description:
When calling with e.g. nstr(0.3333333432674419, { maxDecimals: 0 }), the function returns an empty string ("") instead of "0". This happens because "0".replace(/\.?0+$/, '') results in "". The expected result is "0".

Steps to reproduce:

nstr(0.3333333432674419, { maxDecimals: 0 }) // returns "", should return "0"

Possible fixes:

  • Option 1: Add a check after stripping zeros to ensure the result is never an empty string:

    let result = str.replace(/\.?0+$/, '')
    if (result === '') result = '0'
  • Option 2 (Recommended): Use a safer regex that only removes trailing zeros after a decimal point:

    let result = str.includes('.') ? str.replace(/\.?0+$/, '') : str

    or

    let result = str.replace(/\.0*$/, '')

    This way, "0" is left untouched and only meaningful decimal parts are affected.

I would recommend option 2, as it avoids additional conditional checks and keeps the code simple and robust. It safely leaves "0" unchanged and only affects numbers with decimal places.

Expected behavior:
The function should return "0" instead of an empty string in these cases.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions