【问题标题】:How to calculate a percentage from BigInt?如何从 BigInt 计算百分比?
【发布时间】:2020-11-15 14:30:27
【问题描述】:

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

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

【问题讨论】:

  • BigDecimal 怎么样?

标签: javascript bigint


【解决方案1】:

由于您需要 [0, 100] 范围内的百分比,您可以将 current_hp 乘以 100n

current_hp_percentage = current_hp * 100n / max_hp

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

current_hp_percentage = parseInt(current_hp * 10000n / max_hp) / 100

【讨论】:

    猜你喜欢
    • 2021-04-12
    • 2017-01-24
    • 1970-01-01
    • 2023-02-01
    • 2021-05-26
    • 2011-06-01
    • 2021-01-10
    相关资源
    最近更新 更多