### Install and Build BigNumber.js Source: https://github.com/mikemcl/bignumber.js/blob/main/README.md Install the library and run the build script to create distributable files for different module formats. Requires Node.js. ```bash npm install npm run build # or: node build.js ``` -------------------------------- ### Install BigNumber.js in Node.js Source: https://github.com/mikemcl/bignumber.js/blob/main/README.md Install the library using npm for use in Node.js projects. ```bash npm install bignumber.js ``` -------------------------------- ### Install Terser Source: https://github.com/mikemcl/bignumber.js/blob/main/README.md Install the terser tool globally for minifying JavaScript files. ```bash npm install -g terser ``` -------------------------------- ### Start Benchmark Source: https://github.com/mikemcl/bignumber.js/blob/main/perf/bignumber-vs-bigdecimal.html Initiates the benchmark process. Sets up configuration based on user inputs like digits, operations, and precision. ```javascript begin = function () { var i; clear(); targetReps = +$REPS.value; if (!(targetReps > 0)) return; $START.innerHTML = 'Restart'; i = +$DIGITS.value; $DIGITS.value = maxDigits = i && isFinite(i) ? i : DEFAULT_DIGITS; for (i = 0; i < 9; i++) { if ($INPUTS[i].checked) { bnM = bnMs[$INPUTS[i].id]; bdM = bdMs[$INPUTS[i].id]; break; } } if (bdM == 'divide') { i = +$DP.value; $DP.value = decimalPlaces = isFinite(i) ? i : DEFAULT_DECIMAL_PLACES; rounding = +$R.selectedIndex; BigNumber.config({ DECIMAL_PLACES: decimalPlaces, ROUNDING_MODE: rounding }); } isFixed = $FIX.checked; isIntOnly = $INT.checked; showAll = $SHOW.checked; BigDecimal = (isGWT = $GWT.checked) ? (isIntOnly ? BigInteger : BigDecimal_GWT) : BigDecimal_ICU4J; prevCycleReps = cycleLimit = completedReps = bdTotal = bnTotal = 0; pause = false; cycleReps = showAll ? 1 : 0.5; cycleTime = +new Date(); setTimeout(updateCounter, 0); } ``` -------------------------------- ### Get Help for bigtime.js Source: https://github.com/mikemcl/bignumber.js/blob/main/perf/README.md Run this command to view the help message for the bigtime.js script, which outlines available options and usage. ```bash $ node bigtime -h ``` -------------------------------- ### BigNumber Properties Example Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Demonstrates accessing the coefficient (c), exponent (e), and sign (s) properties of a BigNumber instance. ```javascript x = new BigNumber(0.123) // '0.123' x.toExponential() // '1.23e-1' x.c // '1,2,3' x.e // -1 x.s // 1 y = new Number(-123.4567000e+2) // '-12345.67' y.toExponential() // '-1.234567e+4' z = new BigNumber('-123.4567000e+2') // '-12345.67' z.toExponential() // '-1.234567e+4' z.c // '1,2,3,4,5,6,7' z.e // 4 z.s // -1 ``` -------------------------------- ### Custom Rounding Method Example Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Demonstrates adding a custom prototype method `round` that emulates `Math.round` using `integerValue`. ```javascript BigNumber.prototype.round = function () { return this.integerValue(BigNumber.ROUND_HALF_CEIL); }; x.round() // '123' ``` -------------------------------- ### Using Custom ceil Method with BigNumber Source: https://github.com/mikemcl/bignumber.js/wiki/Add-ceil,-floor,-round-and-trunc This example demonstrates how to use the custom ceil method after extending the BigNumber prototype. It creates a BigNumber instance and applies the ceil method to get its ceiling value. ```javascript import BigNumber from "./my-bignumber.mjs" let x = new BigNumber('43253.589807643345'); x.ceil(); // '43254' ``` -------------------------------- ### BigNumber Constructor Error Handling (STRICT mode) Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Shows examples of invalid inputs that result in BigNumber Errors when STRICT mode is enabled. ```javascript new BigNumber('.1*') // '[BigNumber Error] Not a number: .1*' new BigNumber('blurgh') // '[BigNumber Error] Not a number: blurgh' new BigNumber('9', 2) // '[BigNumber Error] Not a base 2 number: 9' ``` -------------------------------- ### Load ICU4J BigDecimal Script Dynamically Source: https://github.com/mikemcl/bignumber.js/blob/main/perf/bignumber-vs-bigdecimal.html Dynamically loads the ICU4J BigDecimal script. Sets up an onload handler to assign the loaded BigDecimal to a global variable and enable the start button once the script is ready. ```javascript BigDecimal_GWT = BigDecimal; BigDecimal = undefined; var script = document.createElement("script"); script.src = ICU4J_URL; script.onload = script.onreadystatechange = function () { if (!script.readyState || /loaded|complete/.test(script.readyState)) { script = null; BigDecimal_ICU4J = BigDecimal; $START.onmousedown = begin; } }; document.getElementsByTagName("head")[0].appendChild(script); ``` -------------------------------- ### Build and Test Big.js Source: https://github.com/mikemcl/bignumber.js/blob/main/README.md Run these commands to build the project and execute the test suite using Node.js. ```bash npm run build npm test # or: node test/test ``` -------------------------------- ### Getting the absolute value Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Use the absoluteValue method or its alias abs to get a BigNumber representing the magnitude of the original number. The return value is always exact. ```javascript x = new BigNumber(-0.8) y = x.absoluteValue() // '0.8' z = y.abs() // '0.8' ``` -------------------------------- ### Get BigNumber as Plain Object Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Use `toObject()` to get a plain object representing the BigNumber's coefficient, exponent, and sign. This object can be used to recreate the BigNumber. ```javascript x = new BigNumber('777.123') obj = x.toObject() // { c: [ 777, 12300000000000 ], e: 2, s: 1 } obj._isBigNumber = true y = new BigNumber(obj) x.isEqualTo(y) // true ``` -------------------------------- ### Get BigNumber Value as String (including negative zero) Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Use `valueOf()` to get the string representation of a BigNumber, similar to `toString()` but without base conversion. It preserves negative zero. ```javascript x = new BigNumber('-0') x.toString() // '0' x.valueOf() // '-0' y = new BigNumber('1.777e+457') y.valueOf() // '1.777e+457' ``` -------------------------------- ### BigNumber Constructor with Different Bases Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Shows how to create BigNumber instances from strings with specified bases, including handling exponential notation and fractional digits. ```javascript new BigNumber(43210) // '43210' new BigNumber('4.321e+4') // '43210' new BigNumber('-735.0918e-430') // '-7.350918e-428' new BigNumber('123412421.234324', 5) // '607236.557696' ``` -------------------------------- ### Initialize BigNumber Instances Source: https://github.com/mikemcl/bignumber.js/blob/main/README.md Create BigNumber instances from Numbers, Strings, BigInts, or other BigNumbers. Use string initialization for precise values. ```javascript let x = new BigNumber(123.4567); let y = BigNumber('123456.7e-3'); let z = new BigNumber(x); x.isEqualTo(y) && y.isEqualTo(z) && x.isEqualTo(z); // true ``` -------------------------------- ### BigNumber Constructor with Binary, Octal, and Hexadecimal Prefixes Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Demonstrates creating BigNumber instances from strings using binary ('0b'), octal ('0o'), and hexadecimal ('0x') prefixes, including fractional parts. ```javascript new BigNumber('-10110100.1', 2) // '-180.5' new BigNumber('-0b10110100.1') // '-180.5' new BigNumber('ff.8', 16) // '255.5' new BigNumber('0xff.8') // '255.5' ``` -------------------------------- ### Converting to Fraction with BigNumber.js Source: https://github.com/mikemcl/bignumber.js/blob/main/README.md Shows how to convert a BigNumber to a fraction using the `toFraction` method, with an optional maximum denominator argument. ```javascript y = new BigNumber(355) pi = y.dividedBy(113) // "3.1415929204" pi.toFraction() // [ "7853982301", "2500000000" ] pi.toFraction(1000) // [ "355", "113" ] ``` -------------------------------- ### Integer Division with BigNumber.js Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Use `dividedToIntegerBy` or `idiv` to get the integer part of a division. Handles various input types and bases. ```javascript x = new BigNumber(5) y = new BigNumber(3) x.dividedToIntegerBy(y) // '1' x.idiv(0.7) // '7' x.idiv('0.f', 16) // '5' ``` -------------------------------- ### BigNumber Constructor Usage Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Demonstrates basic usage of the BigNumber constructor with numeric and BigNumber inputs. The 'new' keyword is optional. ```javascript x = new BigNumber(0.1) // '0.1' // 'new' is optional y = BigNumber(x) // '0.1' ``` -------------------------------- ### Test Single Method Source: https://github.com/mikemcl/bignumber.js/blob/main/README.md Execute tests for a specific method by providing its path. ```bash node test/methods/toFraction ``` -------------------------------- ### BigNumber.decimalPlaces Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Gets or sets the number of decimal places for a BigNumber, with optional rounding. Can round to a specified number of decimal places or return the current count. ```APIDOC ## decimalPlaces ### Description If `dp` is a number, returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode `rm` to a maximum of `dp` decimal places. If `dp` is negative, digits to the left of the decimal point are rounded. If `dp` is omitted, or is `null` or `undefined`, the return value is the number of decimal places of the value of this BigNumber, or `null` if the value of this BigNumber is ±`Infinity` or `NaN`. If `rm` is omitted, or is `null` or `undefined`, [`ROUNDING_MODE`](#rounding-mode) is used. Throws if `dp` or `rm` is invalid. ### Method Signature `.decimalPlaces(dp [, rm])` or `.dp([dp [, rm]])` ### Parameters `dp`: _number_ - The target number of decimal places. Can be negative to round to the left of the decimal point. `rm`: _number_ - The rounding mode to use (0-8). ### Examples ```javascript x = new BigNumber(1234.56) x.decimalPlaces(1) // '1234.6' x.dp() // 2 x.decimalPlaces(2) // '1234.56' x.decimalPlaces(-2) // '1200' x.dp(10) // '1234.56' x.decimalPlaces(0, 1) // '1234' x.dp(0, 6) // '1235' x.decimalPlaces(1, 1) // '1234.5' x.dp(1, BigNumber.ROUND_HALF_EVEN) // '1234.6' x // '1234.56' y = new BigNumber('9.9e-101') y.dp() // 102 ``` ``` -------------------------------- ### Get Random Number for Testing Source: https://github.com/mikemcl/bignumber.js/blob/main/perf/bignumber-vs-bigdecimal.html Generates a random number string for testing. It handles fixed or variable digits, integer-only constraints, and avoids division by zero for 'divide' and 'remainder' operations. ```javascript getRandom = function () { var z, i = 0, // n is the number of digits - 1 n = isFixed ? maxDigits - 1 : Math.random() * (maxDigits || 1) | 0, r = ( Math.random() * 10 | 0 ) + ''; if (n) { if (r == '0') r = isIntOnly ? ( ( Math.random() * 9 | 0 ) + 1 ) + '' : (z = r + '.'); for ( ; i++ < n; r += Math.random() * 10 | 0 ){} if (!z && !isIntOnly && Math.random() > CHANCE_INTEGER) { r = r.slice( 0, i = (Math.random() * n | 0) + 1 ) + '.' + r.slice(i); } } // Avoid division by zero error with division and modulo if ((bdM == 'divide' || bdM == 'remainder') && parseFloat(r) === 0) r = ( ( Math.random() * 9 | 0 ) + 1 ) + ''; return Math.random() > CHANCE_NEGATIVE ? r : '-' + r; } ``` -------------------------------- ### BigNumber Constructor from Plain Object Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Demonstrates advanced usage where a BigNumber instance is created from a plain JavaScript object containing its sign, exponent, and coefficient. ```javascript new BigNumber({ s: 1, e: 2, c: [ 777, 12300000000000 ], _isBigNumber: true }) // '777.123' ``` -------------------------------- ### BigNumber Constructor with Base Conversion and Rounding Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Illustrates how BigNumber instances created with a specified base are converted to decimal and rounded according to DECIMAL_PLACES and ROUNDING_MODE settings. ```javascript BigNumber.config({ DECIMAL_PLACES: 5 }) new BigNumber('xy.z', 36) // '1222.97222' ``` -------------------------------- ### Getting or setting decimal places Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html The decimalPlaces method (or dp) can be used to round a BigNumber to a specified number of decimal places using a given rounding mode. If no arguments are provided, it returns the number of decimal places of the BigNumber. ```javascript x = new BigNumber(1234.56) x.decimalPlaces(1) // '1234.6' x.dp() // 2 x.decimalPlaces(2) // '1234.56' x.decimalPlaces(-2) // '1200' x.dp(10) // '1234.56' x.decimalPlaces(0, 1) // '1234' x.dp(0, 6) // '1235' x.decimalPlaces(1, 1) // '1234.5' x.dp(1, BigNumber.ROUND_HALF_EVEN) // '1234.6' x // '1234.56' ``` ```javascript y = new BigNumber('9.9e-101') y.dp() // 102 ``` -------------------------------- ### Creating Independent BigNumber Constructors Source: https://github.com/mikemcl/bignumber.js/blob/main/README.md Shows how to create multiple BigNumber constructors with independent configurations using `BigNumber.clone()`. ```javascript // Set DECIMAL_PLACES for the original BigNumber constructor BigNumber.set({ DECIMAL_PLACES: 10 }) // Create another BigNumber constructor, optionally passing in a configuration object BN = BigNumber.clone({ DECIMAL_PLACES: 5 }) x = new BigNumber(1) y = new BN(1) x.div(3) // '0.3333333333' y.div(3) // '0.33333' ``` -------------------------------- ### Set precision or get significant digits with precision (sd) Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Rounds the BigNumber to a specified number of significant digits (`d`) using a given rounding mode (`rm`). If `d` is omitted, it returns the number of significant digits. Trailing zeros in the integer part are counted if `d` is true. ```javascript x = new BigNumber(9876.54321) x.precision(6) // '9876.54' x.sd() // 9 x.precision(6, BigNumber.ROUND_UP) // '9876.55' x.sd(2) // '9900' x.precision(2, 1) // '9800' y = new BigNumber(987000) y.precision() // 3 y.sd(true) // 6 ``` -------------------------------- ### Initialize Test Variables for BigNumber.js and BigDecimal Source: https://github.com/mikemcl/bignumber.js/blob/main/perf/bignumber-vs-bigdecimal.html Sets up arrays for method names and initializes variables for performance testing. These include default values for repetitions, digits, decimal places, and rounding modes. ```javascript var i, completedReps, targetReps, cycleReps, cycleTime, prevCycleReps, cycleLimit, maxDigits, isFixed, isIntOnly, decimalPlaces, rounding, calcTimeout, counterTimeout, script, isGWT, BigDecimal_GWT, BigDecimal_ICU4J, bdM, bdTotal, bnM, bnTotal, bdMs = ['add', 'subtract', 'multiply', 'divide', 'remainder', 'compareTo', 'abs', 'negate', 'pow'], bnMs = ['plus', 'minus', 'multipliedBy', 'dividedBy', 'modulo', 'comparedTo', 'absoluteValue', 'negated', 'exponentiatedBy'], lastRounding = 4, pause = false, up = true, timingVisible = false, showAll = false, // Edit defaults here DEFAULT_REPS = 10000, DEFAULT_DIGITS = 20, DEFAULT_DECIMAL_PLACES = 20, DEFAULT_ROUNDING = 4, MAX_POWER = 20, CHANCE_NEGATIVE = 0.5, // 0 (never) to 1 (always) CHANCE_INTEGER = 0.2, // 0 (never) to 1 (always) MAX_RANDOM_EXPONENT = 100, SPACE_BAR = 32, ICU4J_URL = './lib/bigdecimal_ICU4J/BigDecimal-all-last.js' ``` -------------------------------- ### BigNumber.clone() Method Usage Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Shows how to create a new, independent BigNumber constructor with specific configurations by cloning the default constructor. ```javascript BigNumber.config({ DECIMAL_PLACES: 5 }) BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) x = new BigNumber(1) y = new BN(1) x.div(3) // 0.33333 y.div(3) // 0.333333333 // BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) is equivalent to: BN = BigNumber.clone() BN.config({ DECIMAL_PLACES: 9 }) ``` -------------------------------- ### Load BigNumber.js in Deno Source: https://github.com/mikemcl/bignumber.js/blob/main/README.md Import the library in Deno, specifying type definitions and the module path. CDN options are also provided. ```javascript // @deno-types="https://raw.githubusercontent.com/MikeMcl/bignumber.js/main/dist/bignumber.d.mts" import BigNumber from 'https://raw.githubusercontent.com/MikeMcl/bignumber.js/main/dist/bignumber.mjs'; ``` ```javascript // or // @deno-types="https://unpkg.com/bignumber.js@latest/dist/bignumber.d.mts" import { BigNumber } from 'https://unpkg.com/bignumber.js@latest/dist/bignumber.mjs'; ``` -------------------------------- ### config Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Configures global settings for BigNumber operations. ```APIDOC ## config ### Description Sets configuration options for all BigNumber instances. ### Method `BigNumber.config(options)` ### Parameters - **options** (object) - An object containing configuration properties. - **DECIMAL_PLACES** (number) - The number of decimal places to use for division and exponentiation. - **ROUNDING_MODE** (number) - The rounding mode to use for division and exponentiation. - **EXPONENTIAL_AT** (Array) - The exponent values at which to switch to exponential notation. - **RANGE** (Array) - The exponent values at which to switch to exponential notation. - **CRYPTO** (boolean) - Whether to use crypto-secure random number generation. - **STRICT** (boolean) - Whether to throw errors on invalid input. - **MODULO_MODE** (number) - The modulo mode to use. - **POW_PRECISION** (number) - The precision to use for exponentiation. - **FORMAT** (object) - An object defining the format for `toFormat()`. - **ALPHABET** (string) - The alphabet to use for base conversion. ### Example ```javascript BigNumber.config({ DECIMAL_PLACES: 5 }); ``` ``` -------------------------------- ### Time BigNumber.js vs GWT BigDecimal add Method Source: https://github.com/mikemcl/bignumber.js/blob/main/perf/README.md Use this command to time operations and verify results. It runs a specified number of iterations with random operands of a given digit count. ```bash $ node bigtime plus 10000 40 ``` -------------------------------- ### Initialize Benchmark State Source: https://github.com/mikemcl/bignumber.js/blob/main/perf/bignumber-vs-bigdecimal.html Resets the UI and internal state for a new benchmark run. Clears timers and resets counters. ```javascript clear = function () { clearTimeout(calcTimeout); clearTimeout(counterTimeout); $COUNTER.style.textDecoration = 'none'; $COUNTER.innerHTML = '0'; $TIME.innerHTML = $RESULTS.innerHTML = ''; $START.innerHTML = 'Start'; } ``` -------------------------------- ### Basic BigNumber Operations Source: https://github.com/mikemcl/bignumber.js/blob/main/README.md Demonstrates common arithmetic operations like division, square root, exponentiation, and multiplication with precision control. ```javascript z = x.dividedBy(y) // "0.6666666667" z.squareRoot() // "0.8164965809" z.exponentiatedBy(-3) // "3.3749999995" z.toString(2) // "0.1010101011" z.multipliedBy(z) // "0.44444444448888888889" z.multipliedBy(z).decimalPlaces(10) // "0.4444444445" ``` -------------------------------- ### Configure BigNumber Methods and UI Source: https://github.com/mikemcl/bignumber.js/blob/main/perf/bignumber-vs-bigdecimal.html Sets up event handlers for radio buttons that select BigNumber methods. Updates the UI to reflect the chosen method and enables/disables specific options like rounding mode based on the selection. ```javascript for (i = 0; i < 9; i++) { $INPUTS[i].checked = false; $INPUTS[i].disabled = false; $INPUTS[i].onclick = function () { clear(); lastRounding = $R.options.selectedIndex; $DIV.style.display = 'none'; bnM = bnMs[this.id]; $BD.innerHTML = bdM = bdMs[this.id]; }; } $INPUTS[1].onclick = function () { clear(); $R.options.selectedIndex = lastRounding; $DIV.style.display = 'block'; bnM = bnMs[this.id]; $BD.innerHTML = bdM = bdMs[this.id]; }; ``` -------------------------------- ### BigNumber.config Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Configures the settings for the current BigNumber constructor. ```APIDOC ## .config(object) ### Description Configures the settings for this particular BigNumber constructor. ### Method `BigNumber.config(object)` ### Parameters - **object** (object) - An object that contains some or all of the following properties: - `DECIMAL_PLACES` (number): Integer, `0` to `1e+9` inclusive. Default value: `20`. - `ROUNDING_MODE` (number): Integer, `0` to `8` inclusive. Default value: `4`. - `EXPONENTIAL_AT` (Array): Array of two integers. Default value: `[-7, 20]`. - `RANGE` (Array): Array of two integers. Default value: `[-1e+9, 1e+9]`. - `ENABLE_ গোলাY_FORMAT` (boolean): Default value: `true`. - `ENABLE_ROUNDING_MODE_0001` (boolean): Default value: `false`. - `ENABLE_BIG_NUMBER_ERRORS` (boolean): Default value: `true`. - `USE_BIG_NUMBER_ERRORS` (boolean): Default value: `true`. - `CRYPTO` (boolean): Default value: `false`. - `MODULUS_NORMALIZATION` (boolean): Default value: `true`. - `ALPHABET` (string): Default value: `'0123456789abcdefghijklmnopqrstuvwxyz'`. Used for bases greater than 10. - `STRICT` (boolean): Default value: `true`. ### Returns - `object` - The configuration object. ### Examples ```javascript BigNumber.config({ DECIMAL_PLACES: 5 }) BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_HALF_UP }) ``` ``` -------------------------------- ### Load BigNumber.js in Browser Source: https://github.com/mikemcl/bignumber.js/blob/main/README.md Include the library in your HTML using a script tag. A minified version is available via CDN. ```html ``` ```html ``` -------------------------------- ### Load BigNumber.js in Node.js (ES Module) Source: https://github.com/mikemcl/bignumber.js/blob/main/README.md Import the library using ES module syntax. You can also test local builds. ```javascript import BigNumber from 'bignumber.js'; // or import { BigNumber } from 'bignumber.js'; // or, testing from a local repo: import { BigNumber } from './dist/bignumber.mjs'; ``` -------------------------------- ### BigNumber Constructor with Large Numbers Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Demonstrates creating BigNumber instances from very large numeric strings, including those in exponential notation with large exponents. ```javascript new BigNumber('5032485723458348569331745.33434346346912144534543') new BigNumber('4.321e10000000') ``` -------------------------------- ### Rounding and Truncating Numbers with bignumber.js Source: https://github.com/mikemcl/bignumber.js/wiki/Home Demonstrates the usage of ceil, floor, round, and trunc methods for precise numerical manipulation. Ensure the BigNumber library is imported before use. ```javascript var x = new BigNumber(1.23456789); x.ceil().toString(); // "2" x.floor().toString(); // "1" x.round().toString(); // "1" x.trunc().toString(); // "1" x = new BigNumber(-1.23456789); x.ceil().toString(); // "-1" x.floor().toString(); // "-2" x.round().toString(); // "-1" x.trunc().toString(); // "-1" x = new BigNumber(100, 10); x.toExponential(); // "1e+2" x.toFixed(); // "100" x.toString(); // "100" x.toPrecision(); // "100" x.toString(10); // "100" x = new BigNumber(1.23456789); x.toExponential(2); // "1.23e+0" x.toFixed(2); // "1.23" x.toPrecision(2); // "1.23" x = new BigNumber(1.23456789); x.toExponential(2, 10); // "1.23e+0" x.toFixed(2, 10); // "1.23" x.toPrecision(2, 10); // "1.23" x = new BigNumber(1.23456789); x.toExponential(2, 10, 1); // "1.23e+0" x.toFixed(2, 10, 1); // "1.23" x.toPrecision(2, 10, 1); // "1.23" x = new BigNumber(1.23456789); x.toExponential(2, 10, 1, 1); // "1.23e+0" x.toFixed(2, 10, 1, 1); // "1.23" x.toPrecision(2, 10, 1, 1); // "1.23" x = new BigNumber(1.23456789); x.toExponential(2, 10, 1, 1, 1); // "1.23e+0" x.toFixed(2, 10, 1, 1, 1); // "1.23" x.toPrecision(2, 10, 1, 1, 1); // "1.23" ``` -------------------------------- ### Catch BigNumber Configuration Errors Source: https://github.com/mikemcl/bignumber.js/blob/main/test/console-errors.html Shows how to catch errors when configuring BigNumber.js with invalid settings. Ensure configuration values are of the correct type and within acceptable ranges. ```javascript try { BigNumber.config({ DECIMAL_PLACES: '10.3' }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ DECIMAL_PLACES: 10.3 }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ DECIMAL_PLACES: -1 }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ ROUNDING_MODE: '4.3' }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ ROUNDING_MODE: 4.3 }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ ROUNDING_MODE: 10 }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ EXPONENTIAL_AT: '10.3' }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ EXPONENTIAL_AT: 10.3 }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ EXPONENTIAL_AT: 1e99 }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ RANGE: '1.999' }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ RANGE: 1.999 }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ RANGE: 0 }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ RANGE: 1e99 }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ FORMAT: 1 }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ CRYPTO: 'ugh' }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ MODULO_MODE: '6.6' }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ MODULO_MODE: 6.6 }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ MODULO_MODE: 1e99 }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ POW_PRECISION: '1.1' }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ POW_PRECISION: 1.1 }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ POW_PRECISION: -1 }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ ALPHABET: 'a' }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ ALPHABET: 'abc.d' }); } catch (e) { console.error(String(e)); } ``` ```javascript try { BigNumber.config({ ALPHABET: 'abcdb' }); } catch (e) { console.error(String(e)); } ``` -------------------------------- ### Load BigNumber.js as ES Module in Browser Source: https://github.com/mikemcl/bignumber.js/blob/main/README.md Import the library as an ES module in the browser. Minified versions are available via CDN. ```html ``` ```html ``` -------------------------------- ### Handle Spacebar Key Events Source: https://github.com/mikemcl/bignumber.js/blob/main/perf/bignumber-vs-bigdecimal.html Sets up event listeners for keyup and keydown to toggle a 'pause' state using the spacebar. The 'up' flag prevents repeated toggling on a single press. ```javascript document.onkeyup = function (evt) { evt = evt || window.event; if ((evt.keyCode || evt.which) == SPACE_BAR) { up = true; } }; document.onkeydown = function (evt) { evt = evt || window.event; if (up && (evt.keyCode || evt.which) == SPACE_BAR) { pause = !pause; up = false; } }; ``` -------------------------------- ### Handling NaN and Infinity with BigNumber.js Source: https://github.com/mikemcl/bignumber.js/blob/main/README.md Illustrates how `BigNumber.js` handles `NaN` and `Infinity` values and checks for them using `isNaN` and `isFinite` methods. ```javascript x = new BigNumber(NaN) // "NaN" y = new BigNumber(Infinity) // "Infinity" x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite() // true ``` ```javascript BigNumber.set({ STRICT: false }) z = new BigNumber('zzz') z.isNaN() // true ``` -------------------------------- ### fromFormat Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Creates a BigNumber instance from a formatted string. ```APIDOC ## fromFormat ### Description Creates a new BigNumber instance from a formatted string. ### Method `BigNumber.fromFormat(string, format)` ### Parameters - **string** (string) - The formatted string to parse. - **format** (object) - An object defining the format of the string. ### Example ```javascript var x = BigNumber.fromFormat('1,234.56', { groupSeparator: ',' }); ``` ``` -------------------------------- ### Accessing BigNumber Internal Representation Source: https://github.com/mikemcl/bignumber.js/blob/main/README.md Demonstrates how to access the internal representation of a BigNumber, including its coefficient, exponent, and sign. ```javascript x = new BigNumber(-123.456); x.c // [ 123, 45600000000000 ] coefficient (i.e. significand) x.e // 2 exponent x.s // -1 sign ``` -------------------------------- ### Load BigNumber.js in Node.js (CommonJS) Source: https://github.com/mikemcl/bignumber.js/blob/main/README.md Require the library using CommonJS syntax. You can also test local builds. ```javascript const BigNumber = require('bignumber.js'); // or, testing from a local repo: const BigNumber = require('./dist/bignumber.cjs'); ``` -------------------------------- ### Catch BigNumber Constructor Errors Source: https://github.com/mikemcl/bignumber.js/blob/main/test/console-errors.html Demonstrates catching errors when creating BigNumber instances with invalid values or bases. Ensure values are valid numbers or strings and bases are within the supported range. ```javascript var n; try { n = new BigNumber(123, '5.6'); } catch (e) { console.error(String(e)); } ``` ```javascript try { n = new BigNumber(123, 5.6); } catch (e) { console.error(String(e)); } ``` ```javascript try { n = new BigNumber(123, 65); } catch (e) { console.error(String(e)); } ``` ```javascript try { n = new BigNumber(45324542.452466456546456); } catch (e) { console.error(String(e)); } ``` ```javascript try { n = new BigNumber(333, 2); } catch (e) { console.error(String(e)); } ``` ```javascript try { n = new BigNumber('ugh'); } catch (e) { console.error(String(e)); } ``` ```javascript try { n = new BigNumber(1010101110011011, 2); } catch (e) { console.error(String(e)); } ``` -------------------------------- ### BigNumber.set() Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html An alias for BigNumber.config(), providing an alternative way to set configuration options. ```APIDOC ## BigNumber.set([object]) ### Description An alias for `BigNumber.config()`, providing an alternative way to set configuration options for BigNumber.js. ### Method `BigNumber.set(object)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body Accepts the same configuration options as `BigNumber.config()`: - **DECIMAL_PLACES** (number) - **ROUNDING_MODE** (number) - **EXPONENTIAL_AT** (number or array) - **RANGE** (number or array) - **CRYPTO** (boolean) - **STRICT** (boolean) ### Request Example ```json BigNumber.set({ DECIMAL_PLACES: 5 }) BigNumber.set({ ROUNDING_MODE: BigNumber.ROUND_UP }) ``` ### Response #### Success Response (200) Returns the configuration object. #### Response Example ```json { "DECIMAL_PLACES": 5, "ROUNDING_MODE": 4, "EXPONENTIAL_AT": [-7, 21], "RANGE": [-1e+9, 1e+9], "CRYPTO": false, "STRICT": true } ``` ``` -------------------------------- ### BigNumber Constructor with Underscore as Numeric Separator Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Shows how to use underscores as separators in string inputs for the BigNumber constructor, applicable to decimal, hexadecimal, and binary formats. ```javascript new BigNumber('1\_000\_000.000\_5') // '1000000.0005' new BigNumber('0xff\_ff') // '65535' new BigNumber('1010\_1111', 2) // '175' ``` -------------------------------- ### BigNumber.js Comparison Errors (lte) Source: https://github.com/mikemcl/bignumber.js/blob/main/test/console-errors.html Demonstrates error handling for the less than or equal to (lte) method with various invalid inputs. Employ try-catch for managing exceptions. ```javascript try { n = new BigNumber(2).lte(45324542.452466456546456); } catch (e) { console.error(String(e)); } ``` ```javascript try { n = new BigNumber(2).lte(333, 2); } catch (e) { console.error(String(e)); } ``` ```javascript try { n = new BigNumber(2).lte(123, 5.6); } catch (e) { console.error(String(e)); } ``` ```javascript try { n = new BigNumber(2).lte(123, 37); } catch (e) { console.error(String(e)); } ``` ```javascript try { n = new BigNumber(2).lte('ugh'); } catch (e) { console.error(String(e)); } ``` ```javascript try { n = new BigNumber(2).lte(8475698473265965); } catch (e) { console.error(String(e)); } ``` -------------------------------- ### Set Default UI States Source: https://github.com/mikemcl/bignumber.js/blob/main/perf/bignumber-vs-bigdecimal.html Initializes the default state of various UI elements, including checkboxes for GWT, Integer, and Show All options, as well as input fields for repetitions, digits, and decimal places. ```javascript $MAX.checked = $INPUTS[0].checked = $GWT.checked = true; $SHOW.checked = $INT.checked = false; $REPS.value = DEFAULT_REPS; $DIGITS.value = DEFAULT_DIGITS; $DP.value = DEFAULT_DECIMAL_PLACES; $R.option = DEFAULT_ROUNDING; ``` -------------------------------- ### Exponentiation with BigNumber.js Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Calculate powers using `exponentiatedBy` or `pow`. Supports optional modulo and handles negative exponents with rounding. ```javascript Math.pow(0.7, 2) // 0.48999999999999994 x = new BigNumber(0.7) x.exponentiatedBy(2) // '0.49' BigNumber(3).pow(-2) // '0.11111111111111111111' ``` -------------------------------- ### toFormat Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Converts the BigNumber instance to a formatted string. ```APIDOC ## toFormat ### Description Returns a string representation of this BigNumber formatted according to the configuration. ### Method `toFormat(digits)` ### Parameters - **digits** (number) - The number of digits after the decimal point. ### Example ```javascript BigNumber.config({ FORMAT: { groupSeparator: ',', decimalSeparator: '.' } }); var x = new BigNumber(12345.67); x.toFormat(2); // "12,345.67" ``` ``` -------------------------------- ### clone Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Creates a copy of the BigNumber instance. ```APIDOC ## clone ### Description Returns a new BigNumber instance with the same value as this BigNumber. ### Method `clone()` ### Example ```javascript var x = new BigNumber(123); var y = x.clone(); ``` ``` -------------------------------- ### Configure Number Range for Infinity and Zero Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Sets the exponent limits for overflow to Infinity and underflow to zero. A single number sets the maximum magnitude, while an array defines negative and positive limits. ```javascript BigNumber.config({ RANGE: 500 }) ``` ```javascript BigNumber.config().RANGE // [ -500, 500 ] ``` ```javascript new BigNumber('9.999e499') // '9.999e+499' new BigNumber('1e500') // 'Infinity' new BigNumber('1e-499') // '1e-499' new BigNumber('1e-500') // '0' ``` ```javascript BigNumber.config({ RANGE: [-3, 4] }) ``` ```javascript new BigNumber(99999) // '99999' e is only 4 new BigNumber(100000) // 'Infinity' e is 5 new BigNumber(0.001) // '0.01' e is only -3 new BigNumber(0.0001) // '0' e is -4 ``` -------------------------------- ### Display Performance Timings Source: https://github.com/mikemcl/bignumber.js/blob/main/perf/bignumber-vs-bigdecimal.html Formats and displays the performance results for BigNumber.js and BigDecimal, including the time taken in milliseconds and indicating any mismatches found. ```javascript showTimings = function () { var i, bdS, bnS, sp = '', r = bnTotal < bdTotal ? (bnTotal ? bdTotal / bnTotal : bdTotal) : (bdTotal ? bnTotal / bdTotal : bnTotal); bdS = 'BigDecimal: ' + (bdTotal || '<1'); bnS = 'BigNumber: ' + (bnTotal || '<1'); for ( i = bdS.length - bnS.length; i-- > 0; sp += ' '){} bnS = 'BigNumber: ' + sp + (bnTotal || '<1'); $TIME.innerHTML = 'No mismatches
' + bdS + ' ms
' + ``` -------------------------------- ### BigNumber Constructor Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Creates a new BigNumber object. It accepts a number, string, or another BigNumber, with an optional base for string inputs. It supports various notations and special values like Infinity and NaN. ```APIDOC ## BigNumber Constructor ### Description Creates a new instance of a BigNumber object with value `n`. The value `n` can be a number, string, or another BigNumber. An optional `base` can be provided for string inputs, defaulting to 10. ### Method `new BigNumber(n [, base])` or `BigNumber(n [, base])` ### Parameters - **n** (number|string|BigNumber) - The numeric value. - **base** (number) - Optional. An integer between 2 and 36, specifying the base of the input `n` if it's a string. ### Examples ```javascript new BigNumber(0.1) // '0.1' BigNumber(100) // '100' new BigNumber('123412421.234324', 5) // '607236.557696' new BigNumber('-Infinity') // '-Infinity' new BigNumber('0xff.8') // '255.5' new BigNumber('1_000_000.000_5') // '1000000.0005' ``` ### Notes - If `n` is a decimal and `base` is omitted, `n` can be in normal or exponential notation. - If `base` is specified, `n` must be a string in normal notation. - Signed `0`, signed `Infinity`, and `NaN` are supported. - String values can use underscores as numeric separators. - If `n` is a valid numeric value, it is rounded according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings when a `base` is specified. - An exception is thrown if `base` is invalid. - If `n` is an unsupported type or invalid, a BigNumber Error is thrown unless `STRICT` is `false`, in which case `NaN` is returned. ``` -------------------------------- ### toBigInt Source: https://github.com/mikemcl/bignumber.js/blob/main/doc/API.html Converts the BigNumber instance to a BigInt. ```APIDOC ## toBigInt ### Description Returns a BigInt representation of this BigNumber. ### Method `toBigInt()` ### Example ```javascript var x = new BigNumber(10); x.toBigInt(); // 10n ``` ```