Decimal 基础数学运算示例

以下为通过不同构造函数初始化 Decimal 对象的,并进行基础数学运算示例:

import std.math.numeric.*

main() {
    let decimal1: Decimal = Decimal("12345.6789")
    let decimal2: Decimal = Decimal(BigInt("987654321"), 6)
    println("without ctx:")
    println("${decimal1} + ${decimal2} = ${decimal1 + decimal2}")
    println("${decimal1} - ${decimal2} = ${decimal1 - decimal2}")
    println("${decimal1} * ${decimal2} = ${decimal1 * decimal2}")
    println("${decimal1} / ${decimal2} = ${decimal1 / decimal2}")
    let (quo, rem) = decimal1.divAndRem(decimal2)
    println("${decimal1} / ${decimal2} = ${quo} .. ${rem}")
    println("with ctx(precision: 8, HALF_EVEN):")
    let baseOperCtx = DecimalContext(8, HALF_EVEN)
    println("${decimal1} + ${decimal2} = ${decimal1.add(decimal2, baseOperCtx)}")
    println("${decimal1} - ${decimal2} = ${decimal1.sub(decimal2, baseOperCtx)}")
    println("${decimal1} * ${decimal2} = ${decimal1.mul(decimal2, baseOperCtx)}")
    println("${decimal1} / ${decimal2} = ${decimal1.div(decimal2, baseOperCtx)}")
    let (quoWithCtx, remWithCtx) = decimal1.divAndRem(decimal2, baseOperCtx)
    println("${decimal1} / ${decimal2} = ${quoWithCtx} .. ${remWithCtx}")
    return 0
}

运行结果:

without ctx:
12345.6789 + 987.654321 = 13333.333221
12345.6789 - 987.654321 = 11358.024579
12345.6789 * 987.654321 = 12193263.1112635269
12345.6789 / 987.654321 = 12.49999988609375000142382812498220
12345.6789 / 987.654321 = 12 .. 493.827048
with ctx(precision: 8, HALF_EVEN):
12345.6789 + 987.654321 = 13333.333
12345.6789 - 987.654321 = 11358.025
12345.6789 * 987.654321 = 12193263
12345.6789 / 987.654321 = 12.500000
12345.6789 / 987.654321 = 12 .. 493.827048