# jg-bignumber

> Exact decimal math on bignumber.js: rounding modes, formatting, and financial calculations such as percentage changes.

- **Version:** `1.4.0`
- **Runtimes:** Universal
- **Install:** `npm install jg-bignumber`
- **On npm:** [jg-bignumber](https://www.npmjs.com/package/jg-bignumber)
- **Source:** [packages/jg-bignumber](https://github.com/jesusgraterol/jg-packages/tree/main/packages/jg-bignumber)
- **Recipes:** [jg-bignumber recipes](https://jg-packages.jesusgraterol.dev/packages/jg-bignumber/recipes/index.md)

## Usage

Every calculation is exact, then rounded to 2 decimal places with `ROUND_HALF_UP` and returned as a number, unless the configuration asks otherwise:

```ts
import { calculateSum, processValue, prettifyValue } from 'jg-bignumber';

calculateSum([0.1, '0.2', 0.3]); // 0.6, not 0.6000000000000001
processValue(512.155); // 512.16
processValue(19.991, { roundingMode: 'ROUND_CEIL' }); // 20
processValue('0.000001', { decimalPlaces: 6, type: 'string' }); // '0.000001'
prettifyValue(1234.5, { format: { prefix: '$' } }); // '$1,234.5'
prettifyValue(1234.5, { format: { prefix: '$', minimumDecimalPlaces: 2 } }); // '$1,234.50'
prettifyValue(-5, { format: { prefix: '$' } }); // '-$5'
```

Percentages and money:

```ts
import {
  adjustByPercentage,
  calculateExchange,
  calculatePercentageChange,
  calculateWeightedEntry,
} from 'jg-bignumber';

calculatePercentageChange(100, 125); // 25
adjustByPercentage(100, -10); // 90
calculateExchange(100, 65000, { decimalPlaces: 8 }); // 0.00153846
calculateWeightedEntry([
  [100, 2],
  [130, 1],
]); // 110, the average price weighted by amount
```

Store money as an integer count of its smallest unit, such as microcents in a PostgreSQL `BIGINT`, and convert it exactly, never rounding:

```ts
import { applyBasisPoints, fromScaledInteger, toScaledInteger } from 'jg-bignumber';

toScaledInteger('1.23', 8); // 123000000n
toScaledInteger('0.123456789', 8); // throws INVALID_VALUE: the 9th decimal would be lost
toScaledInteger(1e-8, 8); // throws INVALID_VALUE: JavaScript writes it as '1e-8'
fromScaledInteger(123000000n, 8); // '1.23000000'
applyBasisPoints(100000000n, 500); // 5000000n: a 5% commission, rounded down to a whole unit
```

`BigNumber` is the package's own bignumber.js constructor, so creating values with it never changes the global bignumber.js configuration.

## <a id="api-reference"></a>jg-bignumber API reference

Every export of `jg-bignumber@1.4.0`, 33 in all, with its signature, its errors, and an example. It's generated from the package's TSDoc.

- Functions: [`adjustByPercentage`](#api-adjustByPercentage), [`applyBasisPoints`](#api-applyBasisPoints), [`calculateExchange`](#api-calculateExchange), [`calculateExchangeFee`](#api-calculateExchangeFee), [`calculateMax`](#api-calculateMax), [`calculateMean`](#api-calculateMean), [`calculateMedian`](#api-calculateMedian), [`calculateMin`](#api-calculateMin), [`calculatePercentageChange`](#api-calculatePercentageChange), [`calculatePercentageRepresentation`](#api-calculatePercentageRepresentation), [`calculateSum`](#api-calculateSum), [`calculateWeightedEntry`](#api-calculateWeightedEntry), [`fromScaledInteger`](#api-fromScaledInteger), [`getBigNumber`](#api-getBigNumber), [`isBigNumber`](#api-isBigNumber), [`isFloat`](#api-isFloat), [`isInteger`](#api-isInteger), [`isNumber`](#api-isNumber), [`prettifyValue`](#api-prettifyValue), [`processValue`](#api-processValue), [`toScaledInteger`](#api-toScaledInteger)
- Constants: [`BigNumber`](#api-BigNumber), [`ERRORS`](#api-ERRORS)
- Types: [`IBigNumber`](#api-IBigNumber), [`IBigNumberFormat`](#api-IBigNumberFormat), [`IBigNumberRoundingMode`](#api-IBigNumberRoundingMode), [`IBigNumberRoundingModeName`](#api-IBigNumberRoundingModeName), [`IBigNumberToType`](#api-IBigNumberToType), [`IBigNumberValue`](#api-IBigNumberValue), [`IConfig`](#api-IConfig), [`IOutput`](#api-IOutput), [`IPrettifyFormat`](#api-IPrettifyFormat), [`IType`](#api-IType)

### <a id="api-functions"></a>Functions

#### <a id="api-adjustByPercentage"></a>`adjustByPercentage`

*Function*

Changes a value by a percentage: a positive percentage increases it, and a negative one decreases it, to 0 at most. A value of 0 stays 0.

```ts
adjustByPercentage<T extends Partial<IConfig>>(
  value: Value,
  percentage: Value,
  config?: T,
): IOutput<T>
```

**Parameters**

- `value` `Value`: The value to change.
- `percentage` `Value`: The percentage to change it by.
- `config?` `T`: How the result is processed.

**Returns** `IOutput<T>`: The changed value.

**Throws**

- `INVALID_VALUE`: if any of the given values isn't a finite number or BigNumber throws an error
- `INVALID_DECIMAL_PLACES`: if the number of decimal places is invalid for any reason
- `INVALID_ROUNDING_MODE`: if the rounding mode name is not supported
- `INVALID_TYPE`: if the processing type is not supported
- `NEGATIVE_VALUE_NOT_ALLOWED`: if the value is negative

**Example**

```ts
import { adjustByPercentage } from 'jg-bignumber';

adjustByPercentage(100, 25); // => 125
adjustByPercentage(100, -10); // => 90
```

#### <a id="api-applyBasisPoints"></a>`applyBasisPoints`

*Function*

Applies a rate in basis points to an integer count of an amount's smallest unit, such as a 5% commission on a payment in microcents, rounding down to a whole unit, so the result never exceeds what the rate gives. 100 basis points are 1%, and 10,000 are 100%.

```ts
applyBasisPoints(value: bigint, basisPoints: number): bigint
```

**Parameters**

- `value` `bigint`: The amount in the smallest unit, 0 or more.
- `basisPoints` `number`: The rate, a non-negative safe integer; it may exceed 10,000 for more than 100%.

**Returns** `bigint`: `value × basisPoints / 10,000`, rounded down.

**Throws**

- `INVALID_VALUE`: The value must be a bigint.
- `NEGATIVE_VALUE_NOT_ALLOWED`: The value must be greater than or equal to 0.
- `INVALID_VALUE`: The basis points must be a non-negative safe integer.

**Example**

```ts
import { applyBasisPoints } from 'jg-bignumber';

applyBasisPoints(100_000_000n, 500); // => 5000000n
applyBasisPoints(123_000_000n, 1500); // => 18450000n
applyBasisPoints(10_001n, 1); // => 1n
```

#### <a id="api-calculateExchange"></a>`calculateExchange`

*Function*

Calculates the amount of an asset an exchange gives for a value at a rate, such as how much BTC 100 USDT buys at 65,000 USDT per BTC.

```ts
calculateExchange<T extends Partial<IConfig>>(
  value: Value,
  rate: Value,
  config?: T,
): IOutput<T>
```

**Parameters**

- `value` `Value`: The amount being exchanged.
- `rate` `Value`: The price of one unit of the asset received.
- `config?` `T`: How the result is processed.

**Returns** `IOutput<T>`: The amount received.

**Throws**

- `INVALID_VALUE`: if any of the given values isn't a finite number or BigNumber throws an error
- `INVALID_DECIMAL_PLACES`: if the number of decimal places is invalid for any reason
- `INVALID_ROUNDING_MODE`: if the rounding mode name is not supported
- `INVALID_TYPE`: if the processing type is not supported
- `NEGATIVE_VALUE_NOT_ALLOWED`: if the value or rate are not positive

**Example**

```ts
import { calculateExchange } from 'jg-bignumber';

calculateExchange(100, 65000, { decimalPlaces: 8 }); // => 0.00153846
```

#### <a id="api-calculateExchangeFee"></a>`calculateExchangeFee`

*Function*

Calculates the fee charged for an exchange, as a percentage of the value exchanged.

```ts
calculateExchangeFee<T extends Partial<IConfig>>(
  value: Value,
  feePercentage: Value,
  config?: T,
): IOutput<T>
```

**Parameters**

- `value` `Value`: The amount being exchanged.
- `feePercentage` `Value`: The fee, as a percentage.
- `config?` `T`: How the result is processed.

**Returns** `IOutput<T>`: The fee.

**Throws**

- `INVALID_VALUE`: if any of the given values isn't a finite number or BigNumber throws an error
- `INVALID_DECIMAL_PLACES`: if the number of decimal places is invalid for any reason
- `INVALID_ROUNDING_MODE`: if the rounding mode name is not supported
- `INVALID_TYPE`: if the processing type is not supported
- `NEGATIVE_VALUE_NOT_ALLOWED`: if the value or feePercentage are not positive

**Example**

```ts
import { calculateExchangeFee } from 'jg-bignumber';

calculateExchangeFee(1000, 0.1); // => 1
```

#### <a id="api-calculateMax"></a>`calculateMax`

*Function*

Finds the largest value in a list. An empty list returns 0.

```ts
calculateMax<T extends Partial<IConfig>>(
  values: Value[],
  config?: T,
): IOutput<T>
```

**Parameters**

- `values` `Value[]`: The values.
- `config?` `T`: How the result is processed.

**Returns** `IOutput<T>`: The largest value.

**Throws**

- `INVALID_VALUE`: if any of the given values isn't a finite number or BigNumber throws an error
- `INVALID_DECIMAL_PLACES`: if the number of decimal places is invalid for any reason
- `INVALID_ROUNDING_MODE`: if the rounding mode name is not supported
- `INVALID_TYPE`: if the processing type is not supported
- `INVALID_VALUES_ARRAY`: if the provided values arg is not a valid array

**Example**

```ts
import { calculateMax } from 'jg-bignumber';

calculateMax([3, '1.5', 2]); // => 3
```

#### <a id="api-calculateMean"></a>`calculateMean`

*Function*

Calculates the mean of a list of values. An empty list returns 0.

```ts
calculateMean<T extends Partial<IConfig>>(
  values: Value[],
  config?: T,
): IOutput<T>
```

**Parameters**

- `values` `Value[]`: The values.
- `config?` `T`: How the result is processed.

**Returns** `IOutput<T>`: The mean.

**Throws**

- `INVALID_VALUE`: if any of the given values isn't a finite number or BigNumber throws an error
- `INVALID_DECIMAL_PLACES`: if the number of decimal places is invalid for any reason
- `INVALID_ROUNDING_MODE`: if the rounding mode name is not supported
- `INVALID_TYPE`: if the processing type is not supported
- `INVALID_VALUES_ARRAY`: if the provided values arg is not a valid array

**Example**

```ts
import { calculateMean } from 'jg-bignumber';

calculateMean([1, 2, 4]); // => 2.33
```

#### <a id="api-calculateMedian"></a>`calculateMedian`

*Function*

Calculates the median of a list of values: the middle value, or the mean of the two middle values when the list has an even length. An empty list returns 0.

```ts
calculateMedian<T extends Partial<IConfig>>(
  values: Value[],
  config?: T,
): IOutput<T>
```

**Parameters**

- `values` `Value[]`: The values.
- `config?` `T`: How the result is processed.

**Returns** `IOutput<T>`: The median.

**Throws**

- `INVALID_VALUE`: if any of the given values isn't a finite number or BigNumber throws an error
- `INVALID_DECIMAL_PLACES`: if the number of decimal places is invalid for any reason
- `INVALID_ROUNDING_MODE`: if the rounding mode name is not supported
- `INVALID_TYPE`: if the processing type is not supported
- `INVALID_VALUES_ARRAY`: if the provided values arg is not a valid array

**Example**

```ts
import { calculateMedian } from 'jg-bignumber';

calculateMedian([5, 1, 3]); // => 3
calculateMedian([4, 1, 3, 2]); // => 2.5
```

#### <a id="api-calculateMin"></a>`calculateMin`

*Function*

Finds the smallest value in a list. An empty list returns 0.

```ts
calculateMin<T extends Partial<IConfig>>(
  values: Value[],
  config?: T,
): IOutput<T>
```

**Parameters**

- `values` `Value[]`: The values.
- `config?` `T`: How the result is processed.

**Returns** `IOutput<T>`: The smallest value.

**Throws**

- `INVALID_VALUE`: if any of the given values isn't a finite number or BigNumber throws an error
- `INVALID_DECIMAL_PLACES`: if the number of decimal places is invalid for any reason
- `INVALID_ROUNDING_MODE`: if the rounding mode name is not supported
- `INVALID_TYPE`: if the processing type is not supported
- `INVALID_VALUES_ARRAY`: if the provided values arg is not a valid array

**Example**

```ts
import { calculateMin } from 'jg-bignumber';

calculateMin([3, '1.5', 2]); // => 1.5
```

#### <a id="api-calculatePercentageChange"></a>`calculatePercentageChange`

*Function*

Calculates the percentage a value changed by: positive when it increased, negative when it decreased, and 0 when it didn't change. The largest decrease is -100%, returned whenever the new value is 0 or less.

```ts
calculatePercentageChange<T extends Partial<IConfig>>(
  oldValue: Value,
  newValue: Value,
  config?: T,
): IOutput<T>
```

**Parameters**

- `oldValue` `Value`: The value before the change.
- `newValue` `Value`: The value after the change.
- `config?` `T`: How the result is processed.

**Returns** `IOutput<T>`: The percentage change.

**Throws**

- `INVALID_VALUE`: if any of the given values isn't a finite number or BigNumber throws an error
- `INVALID_DECIMAL_PLACES`: if the number of decimal places is invalid for any reason
- `INVALID_ROUNDING_MODE`: if the rounding mode name is not supported
- `INVALID_TYPE`: if the processing type is not supported
- `NEGATIVE_VALUE_NOT_ALLOWED`: if the oldValue is not positive

**Example**

```ts
import { calculatePercentageChange } from 'jg-bignumber';

calculatePercentageChange(100, 125); // => 25
calculatePercentageChange(100, 80); // => -20
calculatePercentageChange(100, 0); // => -100
```

#### <a id="api-calculatePercentageRepresentation"></a>`calculatePercentageRepresentation`

*Function*

Calculates what percentage of a total a value represents.

```ts
calculatePercentageRepresentation<T extends Partial<IConfig>>(
  value: Value,
  total: Value,
  config?: T,
): IOutput<T>
```

**Parameters**

- `value` `Value`: The part.
- `total` `Value`: The total.
- `config?` `T`: How the result is processed.

**Returns** `IOutput<T>`: The percentage.

**Throws**

- `INVALID_VALUE`: if any of the given values isn't a finite number or BigNumber throws an error
- `INVALID_DECIMAL_PLACES`: if the number of decimal places is invalid for any reason
- `INVALID_ROUNDING_MODE`: if the rounding mode name is not supported
- `INVALID_TYPE`: if the processing type is not supported
- `NEGATIVE_VALUE_NOT_ALLOWED`: if the value or total are not positive

**Example**

```ts
import { calculatePercentageRepresentation } from 'jg-bignumber';

calculatePercentageRepresentation(25, 200); // => 12.5
```

#### <a id="api-calculateSum"></a>`calculateSum`

*Function*

Adds up a list of values. An empty list sums to 0.

```ts
calculateSum<T extends Partial<IConfig>>(
  values: Value[],
  config?: T,
): IOutput<T>
```

**Parameters**

- `values` `Value[]`: The values.
- `config?` `T`: How the result is processed.

**Returns** `IOutput<T>`: The sum.

**Throws**

- `INVALID_VALUE`: if any of the given values isn't a finite number or BigNumber throws an error
- `INVALID_DECIMAL_PLACES`: if the number of decimal places is invalid for any reason
- `INVALID_ROUNDING_MODE`: if the rounding mode name is not supported
- `INVALID_TYPE`: if the processing type is not supported
- `INVALID_VALUES_ARRAY`: if the provided values arg is not a valid array

**Example**

```ts
import { calculateSum } from 'jg-bignumber';

calculateSum([0.1, '0.2', 0.3]); // => 0.6
calculateSum([0.1, 0.2], { type: 'string' }); // => '0.3'
```

#### <a id="api-calculateWeightedEntry"></a>`calculateWeightedEntry`

*Function*

Calculates the average entry price of a position bought in several trades, weighting each price by the amount bought. An empty list, or one whose amounts add up to 0, returns 0.

```ts
calculateWeightedEntry<T extends Partial<IConfig>>(
  trades: [Value, Value][],
  config?: T,
): IOutput<T>
```

**Parameters**

- `trades` `[Value, Value][]`: The trades, each as a `[price, amount]` tuple.
- `config?` `T`: How the result is processed.

**Returns** `IOutput<T>`: The weighted average price.

**Throws**

- `INVALID_VALUE`: if any of the given values isn't a finite number or BigNumber throws an error
- `INVALID_DECIMAL_PLACES`: if the number of decimal places is invalid for any reason
- `INVALID_ROUNDING_MODE`: if the rounding mode name is not supported
- `INVALID_TYPE`: if the processing type is not supported
- `INVALID_VALUES_ARRAY`: if the provided values arg is not a valid array

**Example**

```ts
import { calculateWeightedEntry } from 'jg-bignumber';

calculateWeightedEntry([[100, 2], [130, 1]]); // => 110
calculateWeightedEntry([]); // => 0
```

#### <a id="api-fromScaledInteger"></a>`fromScaledInteger`

*Function*

Converts an integer count of an amount's smallest unit, such as microcents, back to the amount as an exact decimal string, with all `decimals` digits and no symbol, separators, or rounding. Pass it to `prettifyValue` to show it to people.

```ts
fromScaledInteger(value: string | bigint, decimals: number): string
```

**Parameters**

- `value` `string | bigint`: The amount in the smallest unit, as a bigint or an integer string, such as a PostgreSQL BIGINT. A string may have surrounding spaces and a sign.
- `decimals` `number`: How many decimals the smallest unit has, such as 8 for microcents.

**Returns** `string`: The amount.

**Throws**

- `INVALID_VALUE`: if the value isn't a bigint or an integer string
- `INVALID_DECIMAL_PLACES`: if decimals isn't an integer from 0 to 100

**Example**

```ts
import { fromScaledInteger } from 'jg-bignumber';

fromScaledInteger(123000000n, 8); // => '1.23000000'
fromScaledInteger('-1', 8); // => '-0.00000001'
fromScaledInteger(1250n, 0); // => '1250'
```

#### <a id="api-getBigNumber"></a>`getBigNumber`

*Function*

Creates a BigNumber from a number, a numeric string, or a BigNumber, which is returned as is. Only finite values are accepted: `NaN` and `±Infinity` are rejected.

```ts
getBigNumber(value: Value): BigNumber
```

**Parameters**

- `value` `Value`: The value.

**Returns** `BigNumber`: The BigNumber.

**Throws**

- `INVALID_VALUE`: if the value isn't a finite number or BigNumber throws an error

**Example**

```ts
import { getBigNumber } from 'jg-bignumber';

getBigNumber('0.1').plus('0.2').toString(); // => '0.3'
```

#### <a id="api-isBigNumber"></a>`isBigNumber`

*Function*

Checks whether a value is a BigNumber instance, from this package or any other copy of bignumber.js.

```ts
isBigNumber(value: unknown): value is BigNumber
```

**Parameters**

- `value` `unknown`: The value.

**Returns** `value is BigNumber`: Whether it's a BigNumber.

**Example**

```ts
import { getBigNumber, isBigNumber } from 'jg-bignumber';

isBigNumber(getBigNumber(1)); // => true
isBigNumber(1); // => false
```

#### <a id="api-isFloat"></a>`isFloat`

*Function*

Checks whether a value is a finite number with a fractional part, in any of the supported types.

```ts
isFloat(value: unknown): boolean
```

**Parameters**

- `value` `unknown`: The value.

**Returns** `boolean`: Whether it's a float.

**Example**

```ts
import { isFloat } from 'jg-bignumber';

isFloat(12.5); // => true
isFloat('12'); // => false
```

#### <a id="api-isInteger"></a>`isInteger`

*Function*

Checks whether a value is a finite integer, in any of the supported types.

```ts
isInteger(value: unknown): boolean
```

**Parameters**

- `value` `unknown`: The value.

**Returns** `boolean`: Whether it's an integer.

**Example**

```ts
import { isInteger } from 'jg-bignumber';

isInteger('12'); // => true
isInteger(12.5); // => false
```

#### <a id="api-isNumber"></a>`isNumber`

*Function*

Checks whether a value is a finite number, numeric string, or BigNumber.

```ts
isNumber(value: unknown): boolean
```

**Parameters**

- `value` `unknown`: The value.

**Returns** `boolean`: Whether it's a finite number.

**Example**

```ts
import { isNumber } from 'jg-bignumber';

isNumber('12.5'); // => true
isNumber(Infinity); // => false
isNumber('abc'); // => false
```

#### <a id="api-prettifyValue"></a>`prettifyValue`

*Function*

Processes a value and formats it for people, with group separators, a prefix, and a suffix. Trailing zeros are dropped, unless `format.minimumDecimalPlaces` keeps them. The sign goes before the prefix, as in `-$5`.

```ts
prettifyValue(
  value: Value,
  config?: { processing?: Partial<IConfig>; format?: IPrettifyFormat },
): string
```

**Parameters**

- `value` `Value`: The value.
- `config?` `{ processing?: Partial<IConfig>; format?: IPrettifyFormat }`: How the value is processed and formatted. Defaults to `{}`.

**Returns** `string`: The formatted value.

**Throws**

- `INVALID_VALUE`: if the value isn't a finite number or BigNumber throws an error
- `INVALID_DECIMAL_PLACES`: if the number of decimal places is invalid for any reason
- `INVALID_ROUNDING_MODE`: if the rounding mode name is not supported
- `INVALID_TYPE`: if the processing type is not supported
- `INVALID_BIGNUMBER_FORMAT`: if any of the format properties are invalid, or minimumDecimalPlaces
- exceeds decimalPlaces

**Example**

```ts
import { prettifyValue } from 'jg-bignumber';

prettifyValue(1234567.891); // => '1,234,567.89'
prettifyValue(1234.5, { format: { prefix: '$' } }); // => '$1,234.5'
prettifyValue(1234.5, { format: { prefix: '$', minimumDecimalPlaces: 2 } }); // => '$1,234.50'
prettifyValue(-5, { format: { prefix: '$' } }); // => '-$5'
```

#### <a id="api-processValue"></a>`processValue`

*Function*

Rounds a value and returns it as the type the configuration asks for: a number by default, or a string or a BigNumber.

```ts
processValue<T extends Partial<IConfig>>(
  value: Value,
  configuration?: T,
): IOutput<T>
```

**Parameters**

- `value` `Value`: The value.
- `configuration?` `T`: The decimal places, rounding mode, and output type.

**Returns** `IOutput<T>`: The processed value.

**Throws**

- `INVALID_VALUE`: if the value isn't a finite number or BigNumber throws an error
- `INVALID_DECIMAL_PLACES`: if the number of decimal places is invalid for any reason
- `INVALID_ROUNDING_MODE`: if the rounding mode name is not supported
- `INVALID_TYPE`: if the processing type is not supported

**Example**

```ts
import { processValue } from 'jg-bignumber';

processValue(512.155); // => 512.16
processValue(512.155, { decimalPlaces: 1, roundingMode: 'ROUND_FLOOR' }); // => 512.1
processValue('0.000001', { decimalPlaces: 6, type: 'string' }); // => '0.000001'
```

#### <a id="api-toScaledInteger"></a>`toScaledInteger`

*Function*

Converts an amount, such as dollars, to an integer count of its smallest unit, such as microcents with 8 decimals, so it can be stored and added up exactly, as in a PostgreSQL BIGINT. It takes a number or a plain decimal string, with surrounding spaces and a leading `+` allowed, and never rounds: scientific notation, including a number JavaScript writes that way, such as `0.00000001`, hex, malformed values, and digits beyond `decimals` other than trailing zeros are rejected. Only the text is read, so `0.1 + 0.2`, which is `0.30000000000000004`, fails rather than becoming a slightly wrong amount.

```ts
toScaledInteger(value: string | number, decimals: number): bigint
```

**Parameters**

- `value` `string | number`: The amount.
- `decimals` `number`: How many decimals the smallest unit has, such as 8 for microcents.

**Returns** `bigint`: The amount in the smallest unit.

**Throws**

- `INVALID_VALUE`: if the value isn't a plain decimal, or has more decimals than `decimals`
- `INVALID_DECIMAL_PLACES`: if decimals isn't an integer from 0 to 100

**Example**

```ts
import { toScaledInteger } from 'jg-bignumber';

toScaledInteger('1.23', 8); // => 123000000n
toScaledInteger(' +0.00000001 ', 8); // => 1n
toScaledInteger(-12.5, 2); // => -1250n
```

### <a id="api-constants"></a>Constants

#### <a id="api-BigNumber"></a>`BigNumber`

*Constant*

The BigNumber constructor every function uses: a clone of bignumber.js's, so the package never changes the global bignumber.js configuration other code relies on. It never switches to exponential notation, and with STRICT off an invalid value becomes NaN instead of throwing, which the package then reports as INVALID_VALUE.

```ts
const BigNumber: typeof BigNumber
```

#### <a id="api-ERRORS"></a>`ERRORS`

*Constant*

the codes of every error the package throws

```ts
const ERRORS: { INVALID_VALUE: "INVALID_VALUE"; INVALID_TYPE: "INVALID_TYPE"; INVALID_ROUNDING_MODE: "INVALID_ROUNDING_MODE"; INVALID_DECIMAL_PLACES: "INVALID_DECIMAL_PLACES"; INVALID_BIGNUMBER_FORMAT: "INVALID_BIGNUMBER_FORMAT"; INVALID_VALUES_ARRAY: "INVALID_VALUES_ARRAY"; NEGATIVE_VALUE_NOT_ALLOWED: "NEGATIVE_VALUE_NOT_ALLOWED" }
```

### <a id="api-types"></a>Types

#### <a id="api-IBigNumber"></a>`IBigNumber`

*Type*

A BigNumber instance, created with `getBigNumber(value)` or the exported `BigNumber` constructor. Every bignumber.js method is available on it.

```ts
type IBigNumber = BigNumber;
```

#### <a id="api-IBigNumberFormat"></a>`IBigNumberFormat`

*Type*

How prettifyValue formats a value, with every setting of bignumber.js's toFormat, defaults in parentheses: prefix (''), negativeSign ('-'), positiveSign (''), decimalSeparator ('.'), groupSeparator (','), groupSize (3), secondaryGroupSize (0), fractionGroupSeparator (' '), fractionGroupSize (0), and suffix ('').

```ts
type IBigNumberFormat = Required<BigNumber.Format>;
```

#### <a id="api-IBigNumberRoundingMode"></a>`IBigNumberRoundingMode`

*Type*

the numeric rounding mode bignumber.js uses for each IBigNumberRoundingModeName

```ts
type IBigNumberRoundingMode = BigNumber.RoundingMode;
```

#### <a id="api-IBigNumberRoundingModeName"></a>`IBigNumberRoundingModeName`

*Type*

How a value is rounded when it has more decimals than allowed: - ROUND_UP: away from zero - ROUND_DOWN: towards zero - ROUND_CEIL: towards Infinity - ROUND_FLOOR: towards -Infinity - ROUND_HALF_UP (default): to the nearest neighbour, away from zero when equidistant - ROUND_HALF_DOWN: to the nearest neighbour, towards zero when equidistant - ROUND_HALF_EVEN: to the nearest neighbour, towards the even one when equidistant - ROUND_HALF_CEIL: to the nearest neighbour, towards Infinity when equidistant - ROUND_HALF_FLOOR: to the nearest neighbour, towards -Infinity when equidistant

```ts
type IBigNumberRoundingModeName = 'ROUND_UP' | 'ROUND_DOWN' | 'ROUND_CEIL' | 'ROUND_FLOOR' | 'ROUND_HALF_UP' | 'ROUND_HALF_DOWN' | 'ROUND_HALF_EVEN' | 'ROUND_HALF_CEIL' | 'ROUND_HALF_FLOOR';
```

#### <a id="api-IBigNumberToType"></a>`IBigNumberToType`

*Type*

the TypeScript type of a value converted to an IType

```ts
type IBigNumberToType<T> = T extends 'string' ? string : T extends 'number' ? number : T extends 'bignumber' ? IBigNumber : never;
```

#### <a id="api-IBigNumberValue"></a>`IBigNumberValue`

*Type*

the values a BigNumber can be created from: numbers, numeric strings, and BigNumbers

```ts
type IBigNumberValue = BigNumber.Value;
```

#### <a id="api-IConfig"></a>`IConfig`

*Type*

how a value is processed

```ts
type IConfig = {
    decimalPlaces: number;
    roundingMode: IBigNumberRoundingModeName;
    type: IType;
};
```

**Members**

- `decimalPlaces: number` (property): the maximum number of decimals in the output. Defaults to 2
- `roundingMode: IBigNumberRoundingModeName` (property): how the value is rounded when it has more decimals. Defaults to 'ROUND_HALF_UP'
- `type: IType` (property): the output's type. Defaults to 'number'

#### <a id="api-IOutput"></a>`IOutput`

*Type*

the return type of a function that processes a value, picked from its configuration's type

```ts
type IOutput<T> = T extends {
    type: 'string';
} ? string : T extends {
    type: 'number';
} ? number : T extends {
    type: 'bignumber';
} ? IBigNumber : number;
```

#### <a id="api-IPrettifyFormat"></a>`IPrettifyFormat`

*Type*

The format prettifyValue takes: any of bignumber.js's toFormat settings, and the fewest decimals it shows, padded with trailing zeros, such as 2 for '$1,234.50'. minimumDecimalPlaces defaults to 0, and can't exceed the processing's decimalPlaces.

```ts
type IPrettifyFormat = Partial<IBigNumberFormat> & {
    minimumDecimalPlaces?: number;
};
```

#### <a id="api-IType"></a>`IType`

*Type*

the type a processed value is returned as

```ts
type IType = 'string' | 'number' | 'bignumber';
```
