【问题标题】:Convert double to BigInteger [duplicate]将双精度转换为 BigInteger [重复]
【发布时间】:2018-07-24 21:45:29
【问题描述】:

如何尽可能准确地将 double 转换为 BigInteger? BigInteger 没有 valueOf(double) 方法。它确实有一个 valueOf(long) 方法,但是通过 long 转换会破坏 2^64 范围之外的任何值,特别是我试图让像 1e100 这样的大数转换为它们对应的整数值到十六或浮点精度允许的如此重要的数字。

【问题讨论】:

  • BigInteger 会将该信息销毁到...
  • 我希望你知道Double.MAX_VALUE 大约是 1.7*10^308...
  • @MartinFrank:BigInteger 没问题。

标签: java floating-point biginteger bigint


【解决方案1】:

您可以将双精度转换为 BigDecimal,然后再转换为 BigInteger:

BigInteger k = BigDecimal.valueOf(doublevalue).toBigInteger();

【讨论】:

    【解决方案2】:

    您可以使用BigDecimal.valueOf(double),然后调用toBigIntegerExact()。喜欢,

    BigInteger bi = BigDecimal.valueOf(Math.PI).toBigIntegerExact();
    

    【讨论】:

    • 这会引发错误,因为 π 无论如何都不完全是 3。如果您想避免错误,请使用toBigInteger()
    猜你喜欢
    • 2017-10-06
    • 2014-01-06
    • 1970-01-01
    • 2017-09-30
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多