English 中文(简体)
使用转换为BD的字符串的BigDecimal除法精度
原标题:BigDecimal division precision using string converted to BD

我正在尝试将字符串值转换为BigDecimal,然后执行计算,但现在的输出与预期的一样。请在下面找到代码:

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Test {
    public static void main(String[] args) {
        BigDecimal b1 = new BigDecimal("320000");
        BigDecimal b2 = new BigDecimal(0.1);
        BigDecimal b3 = new BigDecimal("9.6");

        BigDecimal b5 = new BigDecimal(320000);
        BigDecimal b6 = new BigDecimal(9.6);

        BigDecimal b4 = (
          b1.multiply(b2)
        ).multiply(
          b3.divide(b1, RoundingMode.HALF_UP)
        );
        System.out.println(b4.setScale(4, RoundingMode.HALF_UP));

        BigDecimal b7 = (
          b5.multiply(b2)
        ).multiply(
          b6.divide(b5, RoundingMode.HALF_UP)
        );
        System.out.println(b7.setScale(4, RoundingMode.HALF_UP));
    }
}

两个实例的输出如下所示:

0.0000
0.9600

当我在第二个实例中将数字实例化为BigDecimal而不是从字符串中转换时,我得到了所需的输出。

你能告诉我为什么会发生这种情况吗?我如何在第一个例子中获得0.9600的期望输出。

问题回答

“……你能告诉我为什么会发生这种情况,以及我如何在第一时间获得0.9600的预期输出吗?”

对于除法,请删除舍入模式参数。

b3.divide(b1)

当指定舍入模式时,将导出比例。

Here is the source code used internally by BigDecimal, for that method.
OpenJDK – GitHub – jdk/src/java.base/share/classes/java/math/BigDecimal.java.

在你的内部划分中,它将使用1的量表,从9.6开始。

b3.divide(b1, RoundingMode.HALF_UP)

因此,这将返回0.0,而实际答案是0.00003

请注意,如果需要,可以将比例指定为第二个参数BigDecimal#diver

b3.divide(b1, 5, RoundingMode.HALF_UP)




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签