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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With