(bignumber.js) "decimalPlaces" or "dp" not working

4.3k views Asked by At

I'm creating a idle html5/js game where I use bignumber.js library to be able to store arbitrarly long numbers, as I requirement for a idle game. The problem is that when in the configuration I have the EXPONENTIAL_AT option setted to some number, and after the variable expoent is larger than EXPONENTIAL_AT, the decimalPlaces function don't work, it shows something like "2.93012393841298e+23" even with "largeNumber.decimalPlaces(4)".

Currently, part of the script is somewhat this:

BigNumber.config({
    DECIMAL_PLACES: 4,
    EXPONENTIAL_AT: 16,
    ROUNDING_MODE: BigNumber.ROUND_HALF_UP
});

var largeNumber = new BigNumber("10594.1931247123691823e+23");

console.log(largeNumber.dp(4).toString());

This shows in console: 1.05941931247123691823e+27, so the exponential notation works, but the rounding not.

I don't know what I'm doing wrong or if is a bug, but I would like that this should work as expected.

1

There are 1 answers

0
T.J. Crowder On

Remember that 10594.1931247123691823e+23 (and 1.05941931247123691823e+27) represent this number:

1059419312471236918230000000

As you can see, it doesn't have a fractional portion at all, there are zero significant digits to the right of the decimal point. So .dp(4) isn't going to affect it.

If you had a number with a fractional portion, .dp(4) would work. I've done an example below. For the purposes of the example, I've told BigNumber not to switch to exponential notation until 30 digits, so it's more obvious what's going on. But that's just to show what's going on, it's not a solution, you don't have to do that. There's no problem to solve: Your number is already rounded (in effect); it's a whole number.

Here's the example:

BigNumber.config({
    EXPONENTIAL_AT: 30,
});

// Just for reference:
const yourNumber = new BigNumber("10594.1931247123691823e+23");
console.log(yourNumber.toString());  // 1059419312471236918230000000

// Your number plus six places of fraction:
const num = BigNumber("1059419312471236918230000000.123456");
console.log(num.toString());         // 1059419312471236918230000000.123456

// Rounded:
const rounded = num.dp(4);
console.log(rounded.toString());     // 1059419312471236918230000000.1235
<script src="https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/9.0.0/bignumber.min.js"></script>