在 Kotlin 中乘以小数

Multiply decimals in Kotlin

我正在尝试将两种加密货币相乘,例如,它们的数字是 0.002000.00300。我将它们定义为浮点数,我也尝试过双精度和大小数。但是我正在努力获得我期望的输出。

这是测试:

class MultiplyDecimalTest {

    @Test
    fun `test can multiply two decimal integers`() {
        val a = 0.00200
        val b = 0.00400
        val expected = 0.00800
        val actual = multiplyDecimal(a, b).toDouble()
        assertEquals(expected, actual)
    }
}

当前函数:

fun multiplyDecimal(a: Double, b: Double): BigDecimal {
    return BigDecimal(b).multiply(BigDecimal(a))
}

我是 Kotlin/Java 的新手,所以我怀疑我可能使用了错误类型的整数。

实际结果是:8.0E-6 - 我知道 E-6 是一个指数,我也希望能够像原始值一样格式化它。

BigDecimal is that you must use it literally the whole way through: passing DoubleBigDecimal 的关键部分破坏了您从 BigDecimal 中获得的任何好处。

您必须对结果使用 constructor taking a String, BigDecimal("0.00200") and BigDecimal("0.00400"), with the quotes. Then call multiply on them. You must not call doubleValue()

BigDecimal 上的平等测试也增加了复杂性,需要完全相同的规模。考虑像这样使用 compareToassertTrue(expected.compareTo(actual) == 0).

另一个问题:你的数学不正确。 0.00200 * 0.00400 = 0.000008 而不是 0.00800。

示例代码仅使用 BigDecimal 而避免使用 Double。在 Java 语法中。更正了您的输入。

var a = "0.002000" ;
var b = "0.004000" ;
var expected = "0.000008" ;

var actual = new BigDecimal( a ).multiply( new BigDecimal( b ) ) ;
actual = actual.setScale( new BigDecimal( a ).scale() ) ;  // Set scale of result to match the scale of inputs.
boolean matching = actual.equals( new BigDecimal( expected ) ) ;

看到这个code run live at IdeOne.com

actual: actual: 0.000008

matching: true