Giter Site home page Giter Site logo

mikemcl / bignumber.js Goto Github PK

View Code? Open in Web Editor NEW
6.5K 83.0 740.0 4.62 MB

A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic

Home Page: http://mikemcl.github.io/bignumber.js

License: MIT License

JavaScript 98.91% HTML 1.06% Java 0.03%
bignumber javascript arbitrary-precision decimal-places bigdecimal

bignumber.js's Introduction

bignumber.js

A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic.

npm version npm downloads


Features

  • Integers and decimals
  • Simple API but full-featured
  • Faster, smaller, and perhaps easier to use than JavaScript versions of Java's BigDecimal
  • 8 KB minified and gzipped
  • Replicates the toExponential, toFixed, toPrecision and toString methods of JavaScript's Number type
  • Includes a toFraction and a correctly-rounded squareRoot method
  • Supports cryptographically-secure pseudo-random number generation
  • No dependencies
  • Wide platform compatibility: uses JavaScript 1.5 (ECMAScript 3) features only
  • Comprehensive documentation and test set

API

If a smaller and simpler library is required see big.js. It's less than half the size but only works with decimal numbers and only has half the methods. It also has fewer configuration options than this library, and does not allow NaN or Infinity.

See also decimal.js, which among other things adds support for non-integer powers, and performs all operations to a specified number of significant digits.

Load

The library is the single JavaScript file bignumber.js or ES module bignumber.mjs.

Browser

<script src='path/to/bignumber.js'></script>

ES module

<script type="module">
import BigNumber from './path/to/bignumber.mjs';

Get a minified version from a CDN:

<script src='https://cdn.jsdelivr.net/npm/[email protected]/bignumber.min.js'></script>
npm install bignumber.js
const BigNumber = require('bignumber.js');

ES module

import BigNumber from "bignumber.js";
import { BigNumber } from "./node_modules/bignumber.js/bignumber.mjs";
import BigNumber from 'https://raw.githubusercontent.com/mikemcl/bignumber.js/v9.1.2/bignumber.mjs';
import BigNumber from 'https://unpkg.com/bignumber.js@latest/bignumber.mjs';

Use

The library exports a single constructor function, BigNumber, which accepts a value of type Number, String or BigNumber,

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

To get the string value of a BigNumber use toString() or toFixed(). Using toFixed() prevents exponential notation being returned, no matter how large or small the value.

let x = new BigNumber('1111222233334444555566');
x.toString();                       // "1.111222233334444555566e+21"
x.toFixed();                        // "1111222233334444555566"

If the limited precision of Number values is not well understood, it is recommended to create BigNumbers from String values rather than Number values to avoid a potential loss of precision.

In all further examples below, let, semicolons and toString calls are not shown. If a commented-out value is in quotes it means toString has been called on the preceding expression.

// Precision loss from using numeric literals with more than 15 significant digits.
new BigNumber(1.0000000000000001)         // '1'
new BigNumber(88259496234518.57)          // '88259496234518.56'
new BigNumber(99999999999999999999)       // '100000000000000000000'

// Precision loss from using numeric literals outside the range of Number values.
new BigNumber(2e+308)                     // 'Infinity'
new BigNumber(1e-324)                     // '0'

// Precision loss from the unexpected result of arithmetic with Number values.
new BigNumber(0.7 + 0.1)                  // '0.7999999999999999'

When creating a BigNumber from a Number, note that a BigNumber is created from a Number's decimal toString() value not from its underlying binary value. If the latter is required, then pass the Number's toString(2) value and specify base 2.

new BigNumber(Number.MAX_VALUE.toString(2), 2)

BigNumbers can be created from values in bases from 2 to 36. See ALPHABET to extend this range.

a = new BigNumber(1011, 2)          // "11"
b = new BigNumber('zz.9', 36)       // "1295.25"
c = a.plus(b)                       // "1306.25"

Performance is better if base 10 is NOT specified for decimal values. Only specify base 10 when you want to limit the number of decimal places of the input value to the current DECIMAL_PLACES setting.

A BigNumber is immutable in the sense that it is not changed by its methods.

0.3 - 0.1                           // 0.19999999999999998
x = new BigNumber(0.3)
x.minus(0.1)                        // "0.2"
x                                   // "0.3"

The methods that return a BigNumber can be chained.

x.dividedBy(y).plus(z).times(9)
x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').integerValue()

Some of the longer method names have a shorter alias.

x.squareRoot().dividedBy(y).exponentiatedBy(3).isEqualTo(x.sqrt().div(y).pow(3))    // true
x.modulo(y).multipliedBy(z).eq(x.mod(y).times(z))                                   // true

As with JavaScript's Number type, there are toExponential, toFixed and toPrecision methods.

x = new BigNumber(255.5)
x.toExponential(5)                  // "2.55500e+2"
x.toFixed(5)                        // "255.50000"
x.toPrecision(5)                    // "255.50"
x.toNumber()                        //  255.5

A base can be specified for toString.

Performance is better if base 10 is NOT specified, i.e. use toString() not toString(10). Only specify base 10 when you want to limit the number of decimal places of the string to the current DECIMAL_PLACES setting.

x.toString(16)                     // "ff.8"

There is a toFormat method which may be useful for internationalisation.

y = new BigNumber('1234567.898765')
y.toFormat(2)                       // "1,234,567.90"

The maximum number of decimal places of the result of an operation involving division (i.e. a division, square root, base conversion or negative power operation) is set using the set or config method of the BigNumber constructor.

The other arithmetic operations always give the exact result.

BigNumber.set({ DECIMAL_PLACES: 10, ROUNDING_MODE: 4 })

x = new BigNumber(2)
y = new BigNumber(3)
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"

There is a toFraction method with an optional maximum denominator argument

y = new BigNumber(355)
pi = y.dividedBy(113)               // "3.1415929204"
pi.toFraction()                     // [ "7853982301", "2500000000" ]
pi.toFraction(1000)                 // [ "355", "113" ]

and isNaN and isFinite methods, as NaN and Infinity are valid BigNumber values.

x = new BigNumber(NaN)                                           // "NaN"
y = new BigNumber(Infinity)                                      // "Infinity"
x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite()        // true

The value of a BigNumber is stored in a decimal floating point format in terms of a coefficient, exponent and sign.

x = new BigNumber(-123.456);
x.c                                 // [ 123, 45600000000000 ]  coefficient (i.e. significand)
x.e                                 // 2                        exponent
x.s                                 // -1                       sign

For advanced usage, multiple BigNumber constructors can be created, each with its own independent configuration.

// 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'

To avoid having to call toString or valueOf on a BigNumber to get its value in the Node.js REPL or when using console.log use

BigNumber.prototype[require('util').inspect.custom] = BigNumber.prototype.valueOf;

For further information see the API reference in the doc directory.

Test

The test/modules directory contains the test scripts for each method.

The tests can be run with Node.js or a browser. For Node.js use

npm test

or

node test/test

To test a single method, use, for example

node test/methods/toFraction

For the browser, open test/test.html.

Minify

To minify using, for example, terser

npm install -g terser
terser big.js -c -m -o big.min.js

Licence

The MIT Licence.

See LICENCE.

bignumber.js's People

Contributors

0xj4r avatar albert-iv avatar benjojo avatar cshenoy avatar dalexj avatar evalir avatar frost avatar iamdoron avatar imalfect avatar jbrower2 avatar khangle27 avatar micahu-zz avatar mikemcl avatar mikke avatar mirumirumi avatar pbakondy avatar perrin4869 avatar sandrofigo avatar santosh653 avatar squaremarco avatar sun-zheng-an avatar sz-piotr avatar trbrc avatar ttys026 avatar xotic750 avatar youfoundron avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bignumber.js's Issues

Removing of tags

I was curious why some tags have been deleted. Is there a particular reason to clean up and remove previous tags or was it unintentional?

I was previously using a tag to v1.2.0 in a bower file, upgrading to v1.4.1 isn't an issue luckily.

attempting to invert a number runs out of memory

new BigNumber('0.50000025000012500006').pow(-1).toString()

this should work right? trying to invert the number.

after about 15 seconds I get:
FATAL ERROR: JS Allocation failed - process out of memory
Abort trap: 6

on node.js, version 2.0.3

Why not define Rounding: Decimal Places at BigNumber.config?

First, thanks for this excellent library, much appreciated. I am using it in a financial application and it works great to far. I have the following issue, this is how I use BigNumber.config:

BigNumber.config({ DECIMAL_PLACES: 10 });
BigNumber.config(null, BigNumber.ROUND_HALF_UP):
var ROUNDING_DP = 8

This is how I instantiate:

value = new BigNumber value;
value.toFixed(ROUNDING_DP);

From my understanding the toFixed method takes only the ROUND_HALF_UPproperty from the .config. Wouldn't it be convenient to be able to also do:

BigNumber.config(null, BigNumber.ROUND_HALF_UP, BigNumber.ROUNDING_DP)

and then just:

value.toFixed()

Got 404 with bower install

I install it using bower in my Mac, and serve my sites in vagrant based linux server, and using symlink to share the code between Mac and Linux. and then I got a 404 from nginx in linux server.

2015/04/20 04:58:26 [error] 3133#0: *1 open() "/vagrant/site/www/vendor/bignumber.js/bignumber.js" failed (20: Not a directory), client: 192.168.211.1, server: mydomain, request: "GET /vendor/bignumber.js/bignumber.js HTTP/1.1", host: "mydomain"

I figure it out, there are two ways to solve this:

  • Install this dep with bower inside my linux server
  • Rename the directory name from bignumber.js to bignumber

I didn't know, if this is an bower issue or just because the filesystem' difference between Mac OS and Linux.

If it is not a bower issue, maybe we should consider to make a alias for bower.

Fractional power

console.log(Math.pow(9,0.5)); // outputs 3 as expected
console.log(new BigNumber(9).pow(0.5)); // Uncaught BigNumber Error: pow() exponent not an integer: 0.5

Value of zero is considered negative if produced by adding to a negative number

If you call isNegative() on a number that has a value of zero that was produced by adding the absolute value of a negative number to itself, you get true. It should return false instead.

var BigNumber = require('bignumber.js');
var foo = new BigNumber(0);
console.log('is 0 negative:', foo.isNegative());
console.log('is 0 negative:', foo.minus(1).plus(1).isNegative());

Output is:

is 0 negative: false
is 0 negative: true

Option for "Engineering notation" - With toExponential()

Engineering notation: "the powers of ten must be multiples of three".

It would be nice to have the ability to output 12356 as 12.345e+3, instead of 1.23456e+5.

Either as it's own method toEngineering() - Identical to toExponential() except for the "multiples of three" bit.

OR

As an extra parameter() to toExponential()
(
) Which perhaps could then allow an arbitrary multiple (not just 3)

And if it was possible to query a BigNumber for this "Engineering" exponent as well (similar to BN.e) that would be an extra bonus

lower and upper characters are vice versa

Hi @MikeMcl,
I use this library to convert a uuid to a base62 string:

var BigNumber = require('bignumber.js');

var uuid = "a4ead3da8d164477ac9f197f11ff6c7a";

uu = BigNumber(uuid,16);

var b62 = uu.toString(62);

console.log(uuid);
console.log(b62);

Result:

a4ead3da8d164477ac9f197f11ff6c7a
51c3Bp5gPevldjwJD5Fv6y

Now the same in PHP:

$uuid = "a4ead3da8d164477ac9f197f11ff6c7a";

$b62 = gmp_strval(gmp_init($uuid, 16), 62);

echo $uuid . "\n";
echo $b62 . "\n";

Result:

a4ead3da8d164477ac9f197f11ff6c7a
51C3bP5GpEVLDJWjd5fV6Y

You see that lower and upper characters are vice versa:

51c3Bp5gPevldjwJD5Fv6y - bignumbers.js
51C3bP5GpEVLDJWjd5fV6Y - PHP

Now I wonder if bignumbers.js or the PHP gmp extension has a bug. Or is there no standard how to convert?

Thanks for your help.

Ciao,
korpa

Bitwise operators

Greetings,

Is there any plans to implement bitwise operators?
This library implements them, but it's messy and may not be reliable.

No easy serialization + deserialization

Thanks for this library. It's really great.

I want to be able to pass the results of calculations done with bignumber.js between services. Typically, when something gets sent over the wire, you serialize it with JSON.stringify and then deserialize it with JSON.parse. Doing so with a BigNumber gives something like {"s":1,"e":0,"c":[1]}.

Unfortunately, there doesn't seem to be support in the constructor for doing new BigNumber(JSON.parse("{\"s\":1,\"e\":0,\"c\":[1]}")) and instantiating a new, equivalent BigNumber from those internals. So, at this point, I can send internal values from service to service, but I can't easily rehydrate those numbers unless I'm doing something like .toString() or .toNumber() on the sending side... which is a little janky.

Provide method for moving the decimal point

The docs say that BigNumber.e should be considered read-only, and my testing confirms that setting it is not reliable. It seems that given the internal representation, it should be easy to add a "shift" method that moves the decimal point. This would be equivalent to multiplying/dividing by powers of 10, but much more efficient and not requiring setting DECIMAL_PLACES to much larger numbers (if you have a large number and multiply by 10^(-50), the second term can get truncated to 0, making the result 0).

This would be very useful for the obvious application of multiplying by powers of 10, but also for situations where you need to convert to a different BigNumber representation and you need to extract the first N digits of the mantissa.

Calculating PI to x DP

Hi!

Would you be interested in a function like this?

/*jslint maxerr: 50, indent: 4, browser: true, white: true, devel: true */
/*global BigNumber */

(function() {
    "use strict";

    function pi(digits) {
        digits = Math.floor(digits);
        var config = BigNumber.config(),
            previousConfig = {},
            k = 0,
            prop,
            sum,
            ta,
            tb,
            divisor,
            a,
            b;

        for (prop in config) {
            if (config.hasOwnProperty(prop)) {
                previousConfig[prop] = config[prop];
            }
        }

        BigNumber.config({
            DECIMAL_PLACES : digits,
            ROUNDING_MODE : 4,
            EXPONENTIAL_AT : [-7, 20],
            RANGE : [-1000000000, 1000000000],
            ERRORS : true
        });

        sum = new BigNumber(0);
        a = ta = new BigNumber(16).div(5);
        b = tb = new BigNumber(-4).div(239);
        while (!a.equals(b)) {
            divisor = 2 * k + 1;
            a = ta.div(divisor);
            b = tb.div(divisor);
            sum = sum.plus(a).plus(b);
            ta = ta.neg().div(25);
            tb = tb.neg().div(57121);
            k += 1;
        }

        for (prop in previousConfig) {
            if (previousConfig.hasOwnProperty(prop)) {
                config[prop] = previousConfig[prop];
            }
        }

        return sum;
    }

    console.log(pi(20).toString());
}());

jsfiddle

lowerThan

what's the history with having lessThan as if we're comparing quantities?

there's a properly named greaterThan, and the complement should be lowerThan

15 significant digits for input number type is not enough

The readme says "It accepts a value of type Number, String or BigNumber Object", which would be nice, but which is currently incorrect. BigNumber(Math.random()) and BigNumber(Math.PI) and several other higher-precision numbers fail with the following message:

BigNumber Error: new BigNumber() number type has more than 15 significant digits: [digits]

This has several problems:

  • Math.random() and Math.PI are valid numbers, which should be handled properly.
  • If you're worried about imprecision, allowing and encouraging literal numbers is exactly the wrong thing to allow. Strings literals should be used instead in that case, as you've apparently noted. The current design makes the one decent use of accepting numbers (for example, numbers from a database where you have no control over the precision anyway) more bug-prone (because people can have code that seems to work for a while on some inputs they try and then breaks in production) while making the improper use easier.
  • If you're going to allow conversion of a base two floating point number into a base ten floating point number, you're almost surely introducing error anyway. For instance, you can't tell whether the number that gives the string '0.1' is exactly 1/10 or the result of a calculation that's merely fairly close to 1/10 because of error, yet you accept that number as if it's exactly 1/10. If that possibility of error when the number is merely near 1/10 is acceptable, why not Math.PI?
  • If you're going to keep the error message, the digits in the error message should include the decimal point. There's no point in showing only the digits (are people supposed to count them or something?) rather than the number itself.

Source map file is missing on CDNJS

Linking to "//cdnjs.cloudflare.com/ajax/libs/bignumber.js/2.0.3/bignumber.min.js" will lead to this error:
"GET //cdnjs.cloudflare.com/ajax/libs/bignumber.js/2.0.3/doc/bignumber.js.map 404 (Not Found)".

Please upload the source map file to CDNJS.

It would also be helpful to have an "pretty" version of this lib on CDNJS, even that we have a source map file.

Length of result

Hi Micheal,
thanks for your fantastic library!

I just have a question on result: I need the result to be shorter than 11 digits, even at the cost of losing a little precision.

E.g:
99999999999 x 9999999999 = 9.999999999800000000001e+21
is possible to truncate to 9.999999999e+21?

Thanks for your response,
R.

15 Significant digit limit

I was wondering why the number type input is limited to 15 significant digits when Javascript can represent an integer to 16?

Ie. -9007199254740991 to 9007199254740991

    // Disallow numbers with over 15 significant digits if number type.
    if ( isNum && b > 15 && n.slice(i).length > 15 && +n.slice(i) > 9007199254740991) {

        // 'new BigNumber() number type has more than 15 significant digits: {n}'
        ifExceptionsThrow( orig, 0 )
    }

I'm not suggesting this is the fix/enhancement as I'm sure there is more to it than that.

Precision is still fixed

Consider this code:
BigNumber(2).sqrt().toPrecision(50)

You'd expect this to return the squareroot of 2 with a precision of 50 digits... It does, but not exactly in the way I was hoping:
"1.4142135623730950488000000000000000000000000000000"
A little dissapointing.

As seen here, the squareroot of 2 is irrational, so it can in theory display a (near-)infinite number of digits.

The above result looks like the calculation was processed with an arbitrary but fixed amount of precision, and then displayed.

Fractional Exponents

It would be great if there was a way to do fractional exponents so that:
var number = BigNumber("25").toPower("0.5");
Would equal 5 and not error.

Expecting function toFixed to have a default of 0 decimal places

It would be nice if the function BigNumber.toFixed has a default of 0 decimal places, consistently with the toFixed of Number:

var n = 2.34;
console.log(n.toFixed()); // '2'

var b = new BigNumber(2.34);
console.log(b.toFixed()); // '2.34' -> should return '2' for consistency

ios 8 problem

hello,

this snippet of code doesn't work with ios8

    <script>
        var a = new BigNumber(0.5);
        var b = new BigNumber(0.5);
        a = a.plus(b);
        console.log(+a);
    </script>

console.log print NaN

with a bit of debug i found that the problem is here
xc[b] %= BASE;

here log of safari console

xc[b]
< 100000000000000
BASE
< 100000000000000
xc[b] % BASE
< 2.5333397e-315
a % 1
< 0
1 % 1
< 0

note the 2.5333397e-315 as a result of mod operation....
seems a safari bug, but as you know, it's easy if your lib support browser os rather than ask to steve jobs (rest in peace) to fix safari in the next ios version 👯

for now my (hugly) fix is
if (BASE == xc[b])
xc[b] = 0;
else
xc[b] %= BASE;

in "plus" function

Add missing bower.json

Adding the missing bower.json would be very nice to work with bower. It can download the project but it's not able to know which file to include, which is the exact purpose of the "main" property of the bower.json.

For more infos on how to do it, refer to the following issue: CreateJS/SoundJS#76

Test page displays incorrectly on Opera 12.

test/browser/every-test.html no longer displays correctly on Opera. (This is only an issue with the test page, not the library itself.)

The tests all pass, but the messages displayed seem to indicate some sort of JavaScript caching issue.

The page displays correctly if it is loaded in a private tab: Opera -> Tabs and Windows -> New Private Tab.

Port to Dart Language

Hi Mike,

First up!, my compliments on an awesome library!

Second up!, any plans to port/convert to The Dart Language?

Best Regards,
Ian Williams

P.S. My apologies if this is not the correct place to ask a question rather than post an issue!

Precision not maintained on division

I noticed some unexpected behavior when dividing numbers. In the following example I have set the precision to 10 decimal places. I expected this to be the number of significant digits, but apparently this means the number of significant digits behind the decimal point.

In the following example I would expect each of the results to be in the format 1.666666667e[+-]EXP: each time having 10 digits, and the value of EXP being equal to the exponent of the divided value. Instead, the number of digits varies depending on the values exponent.

BigNumber.config(10);

console.log(new BigNumber('5e-15').div('3').toExponential()); // "0e+0"
console.log(new BigNumber('5e-10').div('3').toExponential()); // "2e-10"
console.log(new BigNumber('5e-5').div('3').toExponential());  // "1.66667e-5"
console.log(new BigNumber('5e+0').div('3').toExponential());  // "1.6666666667e+0"
console.log(new BigNumber('5e+5').div('3').toExponential());  // "1.666666666666667e+5"
console.log(new BigNumber('5e+10').div('3').toExponential()); // "1.66666666666666666667e+10"

Is this intended behavior? If so, is there any workaround so I can actually do divisions on small values without loosing precision?

Did you just delete all tags before 1.4?

I've started getting errors on bower install. I checked the tags page, and all old tags (versions mentioned in the change log) are wiped away.

This can lead to some problems for projects which depend on older versions of bignumber. Can you fix this issue?

Add Log method

Hello and thank you for your work!

Is it possible to add log() method? similar to Math.log()?

Thank you.

Adding support for a built-in Pi value?

I have started using bignumber.js for a project. I needed to do some math that involved the use of Pi in one of the equations. I had to construct a BigNumber for Pi myself and I wonder if it would make more sense to have this (and possibly other standard values) built-in?

Creating the Pi value wasn't straightforward either.

I tried BigNumber(Math.PI); but that gives an error because it has more than 15 significant digits.

This forced me to do something like BigNumber(Math.PI.toFixed(10));.

Seems like it would just be easier if we could do BigNumber.PI;.

Using bignumber with karma, and browserify

I have a project with karma (and jasmine) for testing, and I'm using browserify.
In a production code, for include Bignumber I have this code.

window.BigNumber = require("pathtobignumber/bignumber.js")

But I cant make this work in a testing environment.

tag 1.4.1 deleted

I was using "bignumber.js": "~1.4.1" in my bower.json file. I looks like the 1.4.x tags were deleted and now bower complains with "ENORESTARGET No tag found that was able to satisfy ~1.4.1". Please keep the tags going forward.

'log' in the README image

I see logarithm (log) method in the README image. But it's neither in the documentation nor it is a method.

performance of pow function

I am using bignumber.js for financial calculations, and I noticed that the pow() function can be slow at times. For example, the below takes 4 seconds to execute:

var a = new BigNumber(1.0011012345678).pow(-2000);

Is this expected? If so, are there things that I can do to speed up calculations like this? I know one option is to round to fewer digits before running the pow function, but are there others?

As a comparison, I also use bcmath in PHP, and I noticed the bcpow function returns instantly for the above calculation:

$a = bcpow(1.0011012345678, -2000);

Thanks for your help.

Ryan

Save in cookies

How can I save a big number in cookies and then read it ?

[QT 5.3]Sometimes division fails on ARM processors

We use this library in the calculator app on Ubuntu Touch.

Under certain conditions (on a Nexus 4/7 with QT 5.3 which is connected via usb to the computer) divisions fails bad (1/3 = 0.3 instead 0.333333, 55/2 = 25). See the original bug to more informations.

We find the bug is caused by timing issue with setting and reading the rem[] array in the do/while cycle in division function.

We fixed in a very symple way, we inverted the adding of next digit to the result array and the update of remainder. See this patch.

Are you interesting to have this change in your code?
I know that is a very specific bug about a certain platform, but can happen also on others platforms.

Hoping to have pleased reporting the bug,
Regards,
Riccardo

Error message showing wrong method name.

If a BigNumber method call is followed by a constructor call with a value which throws an error, then that error's message may wrongly attribute the error to the previous method call instead of the BigNumber constructor.

arbitrary length integers

Mike,

May i use this library for arbitrary length integers. e.g. 1000 digits long base 10 numbers ? Excuse me for this hasty question but i was unable to find such example in the description.

toFraction() behavior

Best described by example

http://jsfiddle.net/a6t784am/2/

.toFraction() seems to land on a denominator based around the DECIMAL_PLACES config variable when a MaxD is not supplied. A MaxD in range of a known denominator give the correct solution.

A noConflict method

Would it be possible to have a noConflict method for BigNumber. This would allow me to have a private BigNumber object for use in my library, where I set specific config() options. And it would allow the user to have a global BigNumber where they can have different config() options that will not affect my private copy. I know that using RequireJS or NodeJS will do this for me, but I'm a little stuck with the case where BigNumber is injected or loaded with <script> Or perhaps there is a better way?

FAQ in documentation is stale/incorrect

In the Why are trailing fractional zeros removed from BigNumbers? section:

x = new BigDecimal("1.0")
y = new BigDecimal("1.1000")
z = x.add(y)                      // 2.1000

x = new BigDecimal("1.20")
y = new BigDecimal("3.45000")
z = x.multiply(y)                 // 4.1400000

should be

x = new BigNumber("1.0")
y = new BigNumber("1.1000")
z = x.plus(y)                      // 2.1000

x = new BigNumber("1.20")
y = new BigNumber("3.45000")
z = x.times(y)                 // 4.1400000

Add method to scope config

When using bignumber.js in a larger project there is the possibility that different files in the project will have different configuration requirements. Using a global configuration is unsafe because future changes in unrelated code can break working code. This could be solved by adding a localConfig method that returns a new BigNumber class with class-scoped configuration.

var config = { DECIMAL_PLACES: 100 };
var BigNumber = require(‘bignumber.js’).localConfig(config);

This is backwards compatible; without localConfig it could still use the global configuration.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.