0

By using this website

I can calculate for example

x = 0.28
y = 1e18
x * y = 280,000,000,000,000,000

How can I do this in javascript while x could be any number, including ints, and y could be any other big number like 1e12 or whatever.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

1

You can't mix BigInt with other types in a calculation, so you need to use BigInt for all the operands.

So instead of multiplying the float by 0.28, multiply by 28n and divide by 100n.

console.log((BigInt(1e18) * 28n) / 100n)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • As I said, the numbers can be unknown at runtime – user2640145 Aug 22 '23 at 22:39
  • You need to require the input to be supplied in this form. If 0.28 represents a percentage, ask for the percentage rather than a fraction, so they enter `28` and you do the division by 100 in your code. – Barmar Aug 23 '23 at 14:11
  • Or count the number of digits after the decimal point, then scale up. If they enter `.285`, use `BigInt(Math.round(input*1000))` to convert it, then divide by `1000n`. – Barmar Aug 23 '23 at 14:13