Skip to content

add/subtract loose the scale when value is zero #284

Open
@glureau

Description

@glureau

Describe the bug

Operations like addition or subtraction are loosing the scale when one of the operand value is zero with a scale of zero.

To Reproduce

println((BigDecimal.parseString("1").scale(0) + BigDecimal.parseString("2").scale(1)).scale) // 1
println((BigDecimal.parseString("0").scale(1) + BigDecimal.parseString("2").scale(1)).scale) // 1
println((BigDecimal.parseString("0").scale(0) + BigDecimal.parseString("2").scale(1)).scale) // -1 : KO, expected 1
println((BigDecimal.parseString("1").scale(0) - BigDecimal.parseString("2").scale(1)).scale) // 1
println((BigDecimal.parseString("0").scale(0) - BigDecimal.parseString("2").scale(1)).scale) // -1 : KO, expected 1

Expected behavior
A clear and concise description of what you expected to happen.

Platform

  • tested on JVM, as the code is checking with == ZERO I presume it's impacting every platforms.

Additional context
I read a bit the code, I presume it's related to this initial condition, as decimalMode.isPrecisionUnlimited is true (because I don't really need to define the precision here) then I don't calculate the best scale.

private fun computeMode(other: BigDecimal, op: ScaleOps): DecimalMode {
return if (decimalMode == null ||
decimalMode.isPrecisionUnlimited ||
other.decimalMode == null ||
other.decimalMode.isPrecisionUnlimited
)
DecimalMode.DEFAULT
else {
DecimalMode(
max(decimalMode.decimalPrecision, other.decimalMode.decimalPrecision),
decimalMode.roundingMode,
if (decimalMode.usingScale && other.decimalMode.usingScale)
when (op) {
ScaleOps.Max -> max(decimalMode.scale, other.decimalMode.scale)
ScaleOps.Min -> min(decimalMode.scale, other.decimalMode.scale)
ScaleOps.Add -> decimalMode.scale + other.decimalMode.scale
} else
-1
)
}

I'm open to push a PR if there's a clear way to go. I guess I could change this DEFAULT with a .copy(scale = ...) but no idea if it's the right approach.

PS : Thanks for your work, greatly appreciated!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions