Skip to content

Instantly share code, notes, and snippets.

@JossDev-Morales
Last active October 24, 2023 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JossDev-Morales/2407de5d6967abe426f85eab0afd76c5 to your computer and use it in GitHub Desktop.
Save JossDev-Morales/2407de5d6967abe426f85eab0afd76c5 to your computer and use it in GitHub Desktop.
bignumber.io Documentation

BigNumber.io

'npm link' 'downloads' 'license' Build Status

'repository' 'discord'

Releases Notes

BigNumber.io is a library for javascript operations to be able to handle very large integer numbers and very large decimal numbers, giving you control over this number and facilitating basic mathematics, with good handling of descriptive errors.

Usage

To be able to represent integers you will need the BigInteger class and for decimal numbers the BigDecimal class, both are an abstraction of these number types.

Methods

Arithmetic Methods

  • Addition
  • ReturnAddition
  • Subtraction
  • ReturnSubtraction
  • Multiplication
  • ReturnMultiplication
  • Division
  • ReturnDivision
  • Module
  • ReturnModule
  • Power
  • ReturnPower
  • Squared
  • ReturnSquared
  • Cubed
  • ReturnCubed
  • Abs

Logical Methods

  • gt
  • lt
  • eq
  • gte
  • lte
  • isPrime
  • isComposite
  • isEven
  • isOdd
  • isPositive
  • isNegative
  • isZero

Logical Static Methods

  • greaterThan
  • lessThan
  • isEqualTo
  • greaterOrEqualThan
  • lessOrEqualThan
  • isNaNDecimal (for bigDecimal)
  • isNaNInt (for bigInteger)
  • isDecimal (only in bigDecimal)
  • isSafeInteger
  • isPrime
  • isComposite
  • isEven
  • isOdd
  • isPositive
  • isNegative
  • isZero

Arithmetic Static Methods

  • gaussSumOf
  • getAbs

Conversion Static Methods

  • fromBinary
  • fromOctal
  • fromHexadecimal
  • fromOtherBase
  • baseToDecimal
  • decimalToBase

Other methods that also allow you to use conversion, see the documentation for conversions and the releases notes where we added this behavior.

  • Return
  • SetBigInteger | SetBigDecimal

Non-arithmetic methods

  • Return
  • GetRecord
  • ClearRecord
  • SetBigInteger | SetBigDecimal

BigInteger and Big Decimal classes


Well, this classes are a representation of a big number (BigNumber) that exceeds the javascript limit, its usefull for arithmetic operations with this numbers and give you a record of operations in a BigNumber representation.

It is very simple to use, let's take a look

   //We initialize the value of the representation by passing a value to the constructor
   const MyBigIntegerNumber = new BigInteger('1999999999999999999999')//we initialize the value
   const MyBigDecimalNumber = new BigDecimal('1999999999999999999999.99999999999999999999')//we initialize the value

then, we know how tu use this classes, the next step is to know when to use each one.

So, when should you use each one?

To know when you should use each one, we must first differentiate them, in the case of BigIntegers, this represents integers that exceed the javascript limit, in the case of BigDecimal, this represents decimals that cannot be represented in javascript, therefore the main difference is the type of number

  • BigInteger integers
  • BigDecimal decimals

Now, you have to know how both classes behave and what problems they have

  • BigInteger The class that handles integers by working only with integers, uses fewer resources, it is based on the native BigInt class to work with arithmetic operations, therefore it is fast and accurate.

  • BigDecimal The class that handles decimals can also receive integers, it is based on operations with strings, so it can be very precise although it is less fast, the difference exists but it is not very noticeable.

With this in mind, we can say that there are 2 use cases for BigIntegers and 4 use cases for BigDecimals.

for BigInteger:

  • when you have an integer representable in javascript
  • when you have an integer not representable in javascript that exceeds its safe limit

for BigDecimal:

  • when you have an integer representable in javascript
  • when you have an integer not representable in javascript that exceeds its safe limit
  • when you have a decimal number representable in javascript
  • when you have a decimal number not representable in javascript
so, all cases are useful?

The answer is nah, of course not, generally when you need to represent a number with BigInteger, you really expect it to be a big integer, if you really expect an integer that is possible to represent with javascript, you should use "Number" natively in javascript, therefore this also applies to BigDecimal numbers, even though it accepts integers, you should not use it for that, as it is slower compared to BigInteger, also if you expect a decimal representable in javascript, you should use the native "Number" from javascript.

Quick Start


The arithmetic methods Add, Subtract, Multiplication and Division have a counterpart "Return", which basically derives from the arithmetic method, does not save the result in the object and does not create a record of the operation either, the result of the operation is returned, once this brief explanation is given, let's continue.

Example of Return arithmetic methods:

    // this dont change the current value of your BigInteger
    const MyBigIntegerNumber = new BigInteger('1999999999999999999999').ReturnAddition('1') 
    console.log(MyBigIntegerNumber.Return())// 1999999999999999999999
        // but return the result directly
    console.log(MyBigIntegerNumber.ReturnAddition('1'))// 2000000000000000000000

Addition


Parameters:

  • number like String or Number

Description:

adds two numbers, the number corresponding to the current value plus the one you pass as a parameter to this method and sets the result of the operation as the current value.

Returns:

this object

Subtraction


Parameters:

  • number like String or Number

Description:

subtracts two numbers, the number corresponding to the current value minus the number you pass as a parameter to this method and sets the result of the operation as the current value.

Returns:

this object

Mulptiplication


Parameters:

  • number like String or Number

Description:

multiplies two numbers, the number corresponding to the current value by the number you pass as a parameter to this method and sets the result of the operation as the current value.

Returns:

this object

Division


Parameters:

  • number like String or Number

Description:

divides the number corresponding to the current value by the number you pass as a parameter to this method and sets the result of the operation as the current value.

There are also specific cases for the devision method in the bigdecimal class, in this method the operation is handled differently, to always obtain high precision when taking the difference between the quotient of a division and the rest and add it as a decimal part of the quotient, that is, take the rest to 0, the highest precision is used, but this leads to problems, since there are operations where the result can give a periodic decimal, which tends to infinity. We can not provide a number with infinite decimals, or really if, but algorithmically, it is impossible, at some point it has to stop that number, in addition to the cost in algorithmic efficiency that this implies, the more decimals, the less efficient it is, in time and resources. To solve the problems involved in periodic decimals, I decided to choose to give a complete context to the division, to better and in a personalized way, the behavior of it.

Not everyone needs or wants such high precision, some may want an average precision of 30 or 50 decimal places, or maybe something less, 10 decimal places, or maybe get a high precision but not risk problems of infinite cycles with periodic decimals, for that is the configuration object, which you can now pass when initializing the bigdecimal class, Later I will present you the possible keys of this object and the default values.

  • maxDecimals This configuration rule is to have control over the maximum number of decimals ( This is equivalent to division cycles, in a cycle 2 decimal places are obtained, so the number of cycles is divided by 2 to obtain the number of decimals, if you use 30 as a maximum, this will be divided into 2, giving 15 effective cycles for the response, in this division of cycles, the native division is used, So it may not be such a good idea to use very large numbers or decimals. :D ) you can get, this applies globally within the context of division, that is, regardless of how long an answer is, this rule will limit the maximum number of decimal digits, lowering precision, but increasing efficiency.

    • Default Value Infinity is the default value, since we cannot lower the precision of the method initially, since it is made to obtain the most accurate number possible within a safe range.
  • periodicDecimalsLimit In this rule stipulates the number of decimals before starting to look for a periodic pattern in the answer ( It only applies when the maximum number of decimal places is infinite. ), that is, the greater the number of cycles, the easier it will be to find a pattern, but it may happen that the periodic pattern is small and we have waited to look for the pattern after a large number of cycles, in short, the higher, the fewer cycles will use the pattern finder, which within itself has an efficiency expense.

    • Default Value 50 Decimals Although we wait for the answer to have a minimum of decimals, to apply the periodic decimal search engine, the algorithm works based on division cycles that result in two digits, that is, the search engine applies every two digits after the minimum of digits, in other words it works in search cycles of 2 digits where it does not look for a pattern of 1 digit, if not in pairs of 2 digits, since the pattern occurs in the response of the divisions to bring the remainder to 0.
  • infinitSaver This rule provides a maximum number of decimals before an emergency exit, or in other words, it allows us to have a back exit of an infinite loop of division cycles, this will be the maximum number of emergency decimals, which only applies when the maxDecimals rule is infinite.

    • Default Value 500 Decimals We would really like to provide infinite precision, but it is not possible, so, in case you wanted, you could disable this emergency exit using the value "infinity"

At the same time, take advantage of this object to provide a bit of customization at the time of the divsion by zero, where you can use the rules to handle it, "return" and "error" where you can choose what returns in the case of divsion by zero and if it should throw an error and if it is the case that message should show this error.

Configuration object with default values.

        {
            maxDecimals: Infinity,
            periodicDecimalsLimit:50,
            infinitySaver:500,
            divideByZero: {
                return:Infinity,
                error: {
                    throw: false,
                    message: 'You cant divide by zero'
                }
            }
        }

Returns:

this object

Module


Parameters

  • number like a string or number

Description

Module Get the residue of dividing the current value by the number you pass as a parameter and set the current value whit the residue

Returns

this object

Power


Parameters

  • number like a string or number

Description

Gets the result of exponentiating the current value by the exponent that you pass as a parameter to this method. The exponent will have to be simple, that is, integer and positive, this method does not yet work with negative exponents or decimals, for more, read the release notes where this method was introduced.

Returns

this object

Squared


Description

This method squares the current value and saves the result as the current value

Returns

this object

Cubed


Description

This method gets the current value to the cube and saves it as the current value

Returns

this object

Abs


Description

This method get the absolute value of the current value and returns it

Returns

result as a string representing the absolute value

Return


Parameters

  • radix as a string or number more in the documentation for conversion of bases

Description:

returns the current value as a string representation and now if you pass a radix, Return will convert the current value to a other base.

Returns:

current value as a string

GetRecord


Description:

a log of all operations since the previous record reset

Returns:

record as an object

ClearRecord


Description:

resets the record of operations so far

Returns:

this

Set-CurrentObject


  • BigDecimal
  • BigInteger

Parameters

  • number the number to set the current value
  • radix the base of the number to convert it to a decimal base

Description:

set the current value with the number you pass as a parameter and now you can use a number in another number base, passing another parameter named Radix, indicating the base of the number

Returns:

this

gt


Parameters:

  • number as a string or number

Description:

Compare the current value with a number received as a parameter to know if the current value is greater than this

Returns:

boolean

lt


Parameters:

  • number as a string or number

Description:

Compare the current value with a number received as a parameter to know if the current value is less than this

Returns:

boolean

eq


Parameters:

  • number as a string or number

Description:

Compare the current value with a number received as a parameter to know if the current value is equal to this

Returns:

boolean

gte


Parameters:

  • number as a string or number

Description:

Compare the current value with a number received as a parameter to know if the current value is greater or equal than this

Returns:

boolean

lte


Parameters:

  • number as a string or number

Description:

Compare the current value with a number received as a parameter to know if the current value is less or equal than this

Returns:

boolean

isPrime


Description

Returns true if the current value is prime

Returns

boolean

isComposite


Description

Returns true if the current value is composite

Returns

boolean

isEven


Description

Returns true if the current value is even

Returns

boolean

isOdd


Descripion

Returns true if the current value is odd

Returns

boolean

isPositive


Descripion

Returns true if the current value is positive

Returns

boolean

isNegative


Descripion

Returns true if the current value is negative

Returns

boolean

isZero


Descripion

Returns true if the current value is equals to zero

Returns

boolean

Static Methods

getAbs


Parameters

  • number as a string or number

Description

Get the absolute value of the number you pass as a parameter

Returns

result as a string

gaussSumOf


Parameters

  • number as a string or number

Description

Returns the result of the sum of gauss of the natural numbers between 1 and the number you pass as a parameter

Returns

result as a string

greaterThan


Description

Compare the first parameter with the second to find out if the first parameter is greater than the second parameter.

Parameters

  • number1 The first number
  • number2 The second number

Returns

boolean

lessThan


Description

Compare the first parameter with the second to find out if the first parameter is less than the second parameter.

Parameters

  • number1 The first number
  • number2 The second number

Returns

boolean

isEqualTo


Description

Compare the first parameter with the second to find out if both parameters are the same.

Parameters

  • number1 The first number
  • number2 The second number

Returns

boolean

greaterOrEqualThan


Description

Compare the first parameter with the second to find out if the first parameter is greater than or equal to the second parameter.

Parameters

  • number1 The first number
  • number2 The second number

Returns

boolean

lessOrEqualThan


Description

Compare the first parameter with the second to find out if the first parameter is less than or equal to the second parameter.

Parameters

  • number1 The first number
  • number2 The second number

Returns

boolean

isPrime


Parameters

  • number as a string or number

Description

Returns true if the number is prime

Returns

boolean

isComposite


Parameters

  • number as a string or number

Description

Returns true if the number is composite

Returns

boolean

isEven


Parameters

  • number as a string or number

Description

Returns true if the number is even

Returns

boolean

isOdd


Parameters

  • number as a string or number

Descripion

Returns true if the number is odd

Returns

boolean

isPositive


Parameters

  • number as a string or number

Descripion

Returns true if the number is positive

Returns

boolean

isNegative


Parameters

  • number as a string or number

Descripion

Returns true if the number is negative

Returns

boolean

isZero


Parameters

  • number as a string or number

Descripion

Returns true if the number is equals to zero

Returns

boolean

isNaNDecimal


Parameters

  • number as a string or number

Description

It detects if a number is not a valid decimal, that is, it does not have more than a decimal point, that it has decimal values after the point and does not have Nan type characters.

Parameters

  • number The number

Returns:

boolean

isDecimal


Parameters

  • number as a string or number

Description

It detects if a number is decimal, that is, if it is not "NaNDecimal" and has decimal values.

Parameters

  • number The number

Returns:

boolean

isSafeInteger


Parameters

  • number as a string or number

Description

Detects if a number is an integer between the safe range of JavaScript for integers, starting from the smallest safe to the largest.

Parameters

  • number The number

Returns:

boolean

baseToDecimal


Parameters

  • number as a string in some base

Description

This method convert a number from any base to a decimal number. See the Documentation for conversions

Parameters

  • number The number in som base
  • radix The base of the number

Returns:

string The converted number to decimal

decimalToBase


Parameters

  • number as a string or number

Description

This method convert a decimal number to other base. See the Documentation for conversions

Parameters

  • number The decimal number to convert
  • radix The base to convert the decimal number

Returns:

string The converted decimal number to other base

IsValidNumber

as a plus, you got a function which lets you know if a number as a string is a valid representation, this same functionality is built into the class BigDecimal, feel free to use it to check if a number is valid to be used.

This functionality validates the following points:

  • validates that the number is a string.
  • validates that a number does not have a positive input sign.
  • validates that the decimals are not greater than one decimal, this is the maximum number of decimals allowed.
  • validates that it does not have rare characters in the string for decimal numbers.
  • validates that it does not have rare characters in the string for non-decimal numbers.

Throws:

An error for each validation

Return:

boolean True if it's a valid number

Releases Notes

See the notes for this release here

And, here you cand find the notes for all versions.

License

bignumber.io is MIT Licensed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment