Java 使用 BigDecimal 除法

标签 java rounding division bigdecimal

我是 java 新手,所以我需要你对我正在进行的项目的帮助! 我定义了一些计数器,这些是我将使用的:

int[] acceptCounters = {};
int[] acceptFailCounters = {};

然后我这样写它们来连接数据库,并查看结果:

acceptCounters = guiops.getOfferStatitics(conn, "WS_GET_OFFER_ACCEPT");
acceptFailCounters = guiops.getOfferStatitics(conn, "WS_GET_OFFER_ACCEPT_PURCHASE_FAILED");*

我得到这样的结果(我删除了 HTML 部分):

        *__html parts__*

        <%
            for (int i = 0; i < acceptCounters.length; i++) {
        %>

html 部分

        <%=formatter.format((new BigDecimal(acceptCounters[i] + acceptFailCounters[i])).longValue())%>

        <%
            }
        %>

这些都可以。我想要找到的是成功率,即 acceptCounters/(acceptCounters + AcceptFailCounters) 并查看 2 位小数。为了使它们保持相同的格式,我编写了如下 Java 代码:

html 部分

        <%
            for (int i = 0; i < acceptCounters.length; i++) {
        %>

html 部分

        <%=formatter.format((new BigDecimal(acceptCounters[i] /(acceptCounters[i] + acceptFailCounters[i]))).longValue())%>

        <%
            }
        %>

但我看到的结果是 0。它应该接近 0.75 或其他什么。你能帮我看看成功率吗?我希望它足够清楚。

最佳答案

BigDecimal 有自己的除法。你可以这样使用:

formatter.format((new BigDecimal(acceptCounters[i]).divide(new BigDecimal(acceptCounters[i]),3)).add(new BigDecimal(acceptFailCounters[i]));

BigDecimal java.math.BigDecimal.divide(BigDecimal divisor, int roundingMode)

Returns a BigDecimal whose value is (this / divisor), and whose scale is this.scale(). If rounding must be performed to generate a result with the given scale, the specified rounding mode is applied.

关于Java 使用 BigDecimal 除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45499055/

相关文章:

java - 你能用 Java 复制 Excel 中的 Floor 函数吗?

division - 如何对大量数字(bignums)实现长除法

java - 将父 Activity 的自定义对话框覆盖到所有 View (包括 Android 中的子 Activity)

java - 内存超过给定阈值后暂停所有正在运行的线程

python - 如何在列表或 np.array 中保留尾随零?

mysql - 数据库中的浮点值转换

用于删除 MSWord 生成的 HTML 标记的 Java 类

java - 浮点除法和预先检查值 if eq 的效率

c# - 通过计算和存储倒数进行快速整数除法?

python - 使用groupby对pandas中的多维度数据进行划分