Do not store minus zero in Decimal

This commit is contained in:
DBotThePony 2023-03-13 09:47:37 +07:00
parent 1ed2eb2134
commit de67209d24
Signed by: DBot
GPG Key ID: DCC23B5715498507

View File

@ -182,14 +182,17 @@ class Decimal @JvmOverloads constructor(whole: BigInteger, decimal: Double = 0.0
var decimal = decimal
if (decimal < 1.0 && decimal + EPSILON >= 1.0) {
// разница между дробью и 1 крайне мала
decimal = 1.0
} else if (decimal > -1.0 && decimal - EPSILON <= -1.0) {
// разница между дробью и -1 крайне мала
decimal = -1.0
}
@Suppress("name_shadowing")
var whole = whole
// нормализуем
if (decimal <= -1f || decimal >= 1f) {
val frac = decimal % 1f
whole += BigInteger.valueOf((decimal - frac).toLong())
@ -198,13 +201,8 @@ class Decimal @JvmOverloads constructor(whole: BigInteger, decimal: Double = 0.0
// дробная часть равна или очень близка к нулю
if (weakEqualDoubles(decimal, 0.0)) {
if (!isZero(whole)) {
this.decimal = 0.0
this.whole = whole
} else { // сохраняет минус ноль
this.decimal = decimal
this.whole = whole
}
this.decimal = 0.0
this.whole = whole
// целая часть и дробная часть имеют одинаковые знаки
} else if (decimal > 0.0 && whole.signum() >= 0 || decimal < 0.0 && whole.signum() <= 0) {
this.decimal = decimal
@ -608,21 +606,7 @@ class Decimal @JvmOverloads constructor(whole: BigInteger, decimal: Double = 0.0
}
fun signum(): Int {
val sign = whole.signum()
if (sign != 0) {
return sign
}
// exactly zero
if (decimal == 0.0)
return if (1.0 / decimal > 0) 1 else -1
// inexactly zero
if (weakEqualDoubles(decimal, 0.0))
return 0
return if (decimal > 0.0) 1 else -1
return whole.signum()
}
override fun compareTo(other: Decimal): Int {