0

I'm using big-integer module to deal with big numbers. When I'm trying to calculate the following expression I get 0:

console.log(bigInt('13775000000000000000').divide('2500000000000000000000')); // 0

But when trying to calculate in pure JS numbers it gives me 0.00551:

console.log(13775000000000000000 / 2500000000000000000000); // 0.00551

Why it so?

Erik
  • 14,060
  • 49
  • 132
  • 218
  • 2
    The closest integer to `0.00551` is `0`. – Paul Feb 16 '18 at 20:24
  • 1
    How can I retrieve same result when using `bigInt` library? – Erik Feb 16 '18 at 20:26
  • 2
    Use an arbitrary-precision library like [bignumber](https://www.npmjs.com/package/bignumber.js). You can't do it with [big-integer](https://www.npmjs.com/package/big-integer) since that is only for integers. – Paul Feb 16 '18 at 20:27
  • @Paulpro, thanks for the explanation. This library is that I need :) – Erik Feb 16 '18 at 20:30
  • 1
    @Paulpro That's not the reason. The fractional digits are discarded, no rounding involved. – xehpuk Feb 16 '18 at 20:37
  • @Erik: you do know that integers are so called "whole numbers", and that 0.00551 is not a whole number? In other words, BigIntegers are not a good way to calculate fractions. – Rudy Velthuis Feb 17 '18 at 19:11

2 Answers2

2

From the documentation:

divide(number)

Performs integer division, disregarding the remainder.

So the result is zero.

Community
  • 1
  • 1
fafl
  • 7,222
  • 3
  • 27
  • 50
1

From https://github.com/peterolson/BigInteger.js

divide(number)

Performs integer division, disregarding the remainder.

Divide method performs integer divison.


From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators

1 / 2      // returns 0.5 in JavaScript
1 / 2      // returns 0 in Java 
// (neither number is explicitly a floating point number)

JS's / performs floating point number divison.

0xrgb
  • 94
  • 6