gpt4 book ai didi

java - 正确舍入非终止(无理数)BigDecimal

转载 作者:行者123 更新时间:2023-11-30 04:24:50 25 4
gpt4 key购买 nike

我有一道数学题。我有一个无理数 BigDecimal,我想对其进行四舍五入,但是我想在它开始重复之后对其进行四舍五入(如果有意义的话)。例如,如果我有

0.76489512147147147147147147147147

我希望它四舍五入到

0.76489512147

因为其余的只是 147 次重复出现。

有 Java 功能可以做到这一点吗?或者我需要实现某种算法吗?

谢谢

最佳答案

通过将输出视为字符串并应用一些正则表达式功夫,可以轻松解决该问题:

// Replace the smallest repeating trailing group with 1 copy of itself
String truncated = a.replaceAll("(.+?)(?=\\1+$).*", "$1");

这是一些测试代码:

BigDecimal bd = new BigDecimal("0.76489512147147147147147147147147");
String s = bd.toString();
// Replace the smallest repeating trailing group with 1 copy of itself
String truncated = s.replaceAll("(.+?)(?=\\1+$).*", "$1");
System.out.println(truncated);

输出:

0.76489512147

关于java - 正确舍入非终止(无理数)BigDecimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16204775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com