Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate a percentage from BigInt?

In my code, I have an enemy object who has a current_hp and max_hp. Both are of type BigInt. I am looking to convert that into a percentage but in range(0, 100). How can I do it effectively?

BigInt division rounds to integer, so I can't use fractions and do hp/max_hp.

like image 514
omega Avatar asked Sep 17 '25 03:09

omega


1 Answers

Since you need the percentage in range [0, 100], you can multiply current_hp by 100n:

current_hp_percentage = current_hp * 100n / max_hp

If you need a more accurate percentage (ie: including K decimals), you can further multiply the multiplier by 10K. For example, in order to print 2 decimals, you can use the following code:

current_hp_percentage = parseInt(current_hp * 10000n / max_hp) / 100
like image 191
Andrei Avatar answered Sep 18 '25 18:09

Andrei