aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/at/hannibal2/skyhanni/utils/NumberUtil.kt
blob: 92cbe4d577e0ee25bbd6d796a97ee2eb2f15a4f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package at.hannibal2.skyhanni.utils

import at.hannibal2.skyhanni.utils.LorenzUtils.round
import at.hannibal2.skyhanni.utils.StringUtils.matches
import java.text.NumberFormat
import java.util.Locale
import java.util.TreeMap
import kotlin.math.pow
import kotlin.math.roundToInt

object NumberUtil {

    @JvmField
    val nf: NumberFormat = NumberFormat.getInstance(Locale.US)
    private val suffixes = TreeMap<Long, String>().apply {
        this[1000L] = "k"
        this[1000000L] = "M"
        this[1000000000L] = "B"
        this[1000000000000L] = "T"
        this[1000000000000000L] = "P"
        this[1000000000000000000L] = "E"
    }
    private val romanSymbols = TreeMap(
        mapOf(
            1000 to "M",
            900 to "CM",
            500 to "D",
            400 to "CD",
            100 to "C",
            90 to "XC",
            50 to "L",
            40 to "XL",
            10 to "X",
            9 to "IX",
            5 to "V",
            4 to "IV",
            1 to "I",
        )
    )

    /**
     * This code was modified and taken under CC BY-SA 3.0 license
     * @link https://stackoverflow.com/a/30661479
     * @author assylias
     */

    @JvmStatic
    fun format(value: Number, preciseBillions: Boolean = false): String {
        @Suppress("NAME_SHADOWING")
        val value = value.toLong()
        // Long.MIN_VALUE == -Long.MIN_VALUE so we need an adjustment here
        if (value == Long.MIN_VALUE) return format(Long.MIN_VALUE + 1, preciseBillions)
        if (value < 0) return "-" + format(-value, preciseBillions)

        if (value < 1000) return value.toString() // deal with small numbers

        val (divideBy, suffix) = suffixes.floorEntry(value)

        val truncated = value / (divideBy / 10) // the number part of the output times 10

        val truncatedAt = if (suffix == "M") 1000 else if (suffix == "B") 1000000 else 100

        val hasDecimal = truncated < truncatedAt && truncated / 10.0 != (truncated / 10).toDouble()

        return if (value > 1_000_000_000 && hasDecimal && preciseBillions) {
            val decimalPart = (value % 1_000_000_000) / 1_000_000
            "${truncated / 10}.$decimalPart$suffix"
        } else {
            if (hasDecimal) (truncated / 10.0).toString() + suffix else (truncated / 10).toString() + suffix
        }
    }

    /**
     * This code was unmodified and taken under CC BY-SA 3.0 license
     * @link https://stackoverflow.com/a/22186845
     * @author jpdymond
     */
    fun Double.roundToPrecision(precision: Int): Double { // TODO is this the same as LorenzUtils.round() ?
        val scale = 10.0.pow(precision).toInt()
        return (this * scale).roundToInt().toDouble() / scale
    }

    /**
     * This code was unmodified and taken under CC BY-SA 3.0 license
     * @link https://stackoverflow.com/a/22186845
     * @author jpdymond
     */
    fun Float.roundToPrecision(precision: Int): Float {
        val scale = 10.0.pow(precision).toInt()
        return (this * scale).roundToInt().toFloat() / scale
    }

    fun Number.ordinal(): String {
        val long = this.toLong()
        if (long % 100 in 11..13) return "th"
        return when (long % 10) {
            1L -> "st"
            2L -> "nd"
            3L -> "rd"
            else -> "th"
        }
    }

    fun Number.addSuffix(): String {
        return this.toString() + this.ordinal()
    }

    fun Number.addSeparators() = NumberFormat.getNumberInstance().format(this)

    fun String.romanToDecimalIfNecessary() = toIntOrNull() ?: romanToDecimal()

    /**
     * This code was converted to Kotlin and taken under CC BY-SA 3.0 license
     * @link https://stackoverflow.com/a/9073310
     */
    fun String.romanToDecimal(): Int {
        var decimal = 0
        var lastNumber = 0
        val romanNumeral = this.uppercase()
        for (x in romanNumeral.length - 1 downTo 0) {
            when (romanNumeral[x]) {
                'M' -> {
                    decimal = processDecimal(1000, lastNumber, decimal)
                    lastNumber = 1000
                }

                'D' -> {
                    decimal = processDecimal(500, lastNumber, decimal)
                    lastNumber = 500
                }

                'C' -> {
                    decimal = processDecimal(100, lastNumber, decimal)
                    lastNumber = 100
                }

                'L' -> {
                    decimal = processDecimal(50, lastNumber, decimal)
                    lastNumber = 50
                }

                'X' -> {
                    decimal = processDecimal(10, lastNumber, decimal)
                    lastNumber = 10
                }

                'V' -> {
                    decimal = processDecimal(5, lastNumber, decimal)
                    lastNumber = 5
                }

                'I' -> {
                    decimal = processDecimal(1, lastNumber, decimal)
                    lastNumber = 1
                }
            }
        }
        return decimal
    }

    fun Int.toRoman(): String {
        if (this <= 0) error("$this must be positive!")
        val l = romanSymbols.floorKey(this)
        return if (this == l) {
            romanSymbols[this]!!
        } else romanSymbols[l] + (this - l).toRoman()
    }

    private fun processDecimal(decimal: Int, lastNumber: Int, lastDecimal: Int) = if (lastNumber > decimal) {
        lastDecimal - decimal
    } else {
        lastDecimal + decimal
    }

    val pattern = "^[0-9]*$".toPattern()
    val formatPattern = "^[0-9,.]*[kmb]?$".toPattern()

    fun String.isInt(): Boolean {
        return isNotEmpty() && pattern.matcher(this).matches()
    }

    fun String.isFormatNumber(): Boolean {
        return isNotEmpty() && formatPattern.matches(this)
    }

    fun percentageColor(percentage: Double) = when {
        percentage > 0.9 -> LorenzColor.DARK_GREEN
        percentage > 0.75 -> LorenzColor.GREEN
        percentage > 0.5 -> LorenzColor.YELLOW
        percentage > 0.25 -> LorenzColor.GOLD
        else -> LorenzColor.RED
    }

    fun percentageColor(have: Long, max: Long): LorenzColor = percentageColor(have.fractionOf(max))

    fun Number.percentWithColorCode(max: Number, round: Int = 1): String {
        val fraction = this.fractionOf(max)
        val color = percentageColor(fraction)
        val amount = (fraction * 100.0).round(round)
        return "${color.getChatColor()}$amount%"
    }

    // TODO create new function formatLong, and eventually deprecate this function.
    @Deprecated("renamed", ReplaceWith("this.formatLong()"))
    fun String.formatNumber(): Long = formatLong()

    fun String.formatDouble(): Double =
        formatDoubleOrNull() ?: throw NumberFormatException("formatDouble failed for '$this'")

    fun String.formatLong(): Long =
        formatDoubleOrNull()?.toLong() ?: throw NumberFormatException("formatLong failed for '$this'")

    fun String.formatInt(): Int =
        formatDoubleOrNull()?.toInt() ?: throw NumberFormatException("formatInt failed for '$this'")

    fun String.formatDoubleOrUserError(): Double? = formatDoubleOrNull() ?: run {
        ChatUtils.userError("Not a valid number: '$this'")
        return@run null
    }

    fun String.formatLongOrUserError(): Long? = formatDoubleOrNull()?.toLong() ?: run {
        ChatUtils.userError("Not a valid number: '$this'")
        return@run null
    }

    fun String.formatIntOrUserError(): Int? = formatDoubleOrNull()?.toInt() ?: run {
        ChatUtils.userError("Not a valid number: '$this'")
        return@run null
    }

    private fun String.formatDoubleOrNull(): Double? {
        var text = lowercase().replace(",", "")

        val multiplier = if (text.endsWith("k")) {
            text = text.substring(0, text.length - 1)
            1_000.0
        } else if (text.endsWith("m")) {
            text = text.substring(0, text.length - 1)
            1.milion
        } else if (text.endsWith("b")) {
            text = text.substring(0, text.length - 1)
            1.bilion
        } else 1.0
        return text.toDoubleOrNull()?.let {
            it * multiplier
        }
    }

    val Int.milion get() = this * 1_000_000.0
    private val Int.bilion get() = this * 1_000_000_000.0
    val Double.milion get() = (this * 1_000_000.0).toLong()

    /** @return clamped to [0.0, 1.0]**/
    fun Number.fractionOf(maxValue: Number) = maxValue.toDouble().takeIf { it != 0.0 }?.let { max ->
        this.toDouble() / max
    }?.coerceIn(0.0, 1.0) ?: 1.0

    fun interpolate(now: Float, last: Float, lastUpdate: Long): Float {
        var interp = now
        if (last >= 0 && last != now) {
            var factor: Float = (SimpleTimeMark.now().toMillis() - lastUpdate) / 1000f
            factor = factor.coerceIn(0f, 1f)
            interp = last + (now - last) * factor
        }
        return interp
    }

}