Kotlin / dataframe

Structured data processing in Kotlin
https://kotlin.github.io/dataframe/overview.html
Apache License 2.0
820 stars 58 forks source link

Support additional Number types (like Percentage) #610

Open Jolanrensen opened 7 months ago

Jolanrensen commented 7 months ago

I was experimenting with adding a wrapper around Doubles for percentages, since that's something many other table solutions support.

Something like this works for basic usage:

data class Percentage(val value: Double, val noDecimals: Int = 2) : Number(), Comparable<Percentage> {
    override fun toByte(): Byte = value.toInt().toByte()
    override fun toDouble(): Double = value
    override fun toFloat(): Float = value.toFloat()
    override fun toInt(): Int = value.toInt()
    override fun toLong(): Long = value.toLong()
    override fun toShort(): Short = value.toInt().toShort()
    override fun compareTo(other: Percentage): Int = value.compareTo(other.value)
    override fun toChar(): Char = value.toInt().toChar()

    private fun Double.roundToNoDecimals(noDecimals: Int): Double =
         round(this * 10.0.pow(noDecimals)) / 10.0.pow(noDecimals)

    override fun toString(): String {
        val percentage = value * 100.0
        val double =
            if (noDecimals <= 0) {
                round(percentage).toLong()
            } else {
                percentage.roundToNoDecimals(noDecimals)
            }
        return "$double%"
    }
}

fun Number.toPercentage(noDecimals: Int = 2): Percentage = Percentage(this.toDouble(), noDecimals)

image_720

However, since this is a Number, I was under the impression we supported converting it (among other things) right out of the gate. Unfortunately I was wrong:

image_720

To fully support any new Number implementation, we need: