在转换为 BigDecimal 之前先转换为 String

Long to String before converting to a BigDecimal

我必须将 Long(对象一,包含在变量 'longValueToConvert' 中)转换为 BigDecimal。

我会做这样的事情:

new BigDecimal(longValueToConvert)

但我读到此转换可能会导致转换错误,并且最好先将 Long 转换为 String,然后再将其用于 BigDecimal 构造函数。

new BigDecimal(longValueToConvert.toString())

用第一个好还是第二个好?我用 Java 8.

你听错了。 BigDecimal(long) 构造函数没有转换错误。一个 long 可以被准确地表示出来,并且从中得到一个 BigDecimal 是没有问题的。

只有在使用BigDecimal(double)构造函数时才需要注意。这是因为某些 double 值无法准确表示。来自文档:

The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 [...], but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double [...].

The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.

你可以试试这个:

new BigDecimal(longValueToConvert.longValue())

这很好用。我相信您应该关心的是在表示浮点数时,因为那里的精度很重要。例如当您使用 BigDecimal (double)BigDecimal(float) 构造函数时。这些场景你有吗?另外,这里的名字告诉你一切。 Long 到任何浮点数都不是问题,但是来自其他方向的需要小心。