如何计算 BigInt 的百分比?

ome*_*ega 1 javascript bigint

在我的代码中,我有一个敌对对象,它有一个current_hpmax_hp。两者都是 类型BigInt。我希望将其转换为百分比,但在range(0, 100). 我怎样才能有效地做到这一点?

BigInt除法四舍五入为整数,所以我不能使用分数并做hp/max_hp.

小智 5

既然你需要在区间[0,100]的百分比,你可以乘current_hp100N

current_hp_percentage = current_hp * 100n / max_hp
Run Code Online (Sandbox Code Playgroud)

如果您需要更准确的百分比(即:包括K 位小数),您可以进一步将乘数乘以 10 K。例如,为了打印 2 位小数,您可以使用以下代码:

current_hp_percentage = parseInt(current_hp * 10000n / max_hp) / 100
Run Code Online (Sandbox Code Playgroud)