Twidere-App-Android-Twitter.../twidere/src/main/kotlin/org/mariotaku/ktextension/NumberExtensions.kt

59 lines
1.3 KiB
Kotlin
Raw Normal View History

2016-07-30 02:08:57 +02:00
package org.mariotaku.ktextension
2017-04-20 14:04:37 +02:00
import java.text.NumberFormat
import java.util.*
2016-07-30 02:08:57 +02:00
/**
* Created by mariotaku on 16/7/30.
*/
2017-09-16 17:33:00 +02:00
fun String?.toLongOr(def: Long) = try {
this?.toLong() ?: def
} catch (e: NumberFormatException) {
def
2016-08-29 13:03:55 +02:00
}
2017-09-16 17:33:00 +02:00
fun String?.toIntOr(def: Int) = try {
this?.toInt() ?: def
} catch (e: NumberFormatException) {
def
2016-12-03 16:45:13 +01:00
}
2017-09-16 17:33:00 +02:00
fun String?.toDoubleOr(def: Double) = try {
this?.toDouble() ?: def
} catch (e: NumberFormatException) {
def
2017-01-31 05:04:36 +01:00
}
fun Int.coerceInOr(range: ClosedRange<Int>, def: Int): Int {
if (range.isEmpty()) return def
2017-01-31 05:04:36 +01:00
return coerceIn(range)
}
/**
* Convenience method checking int flags
*/
operator fun Int.contains(i: Int): Boolean = (this and i) == i
/**
* Convenience method checking long flags
*/
2017-04-20 14:04:37 +02:00
operator fun Long.contains(i: Long): Boolean = (this and i) == i
fun Number.toLocalizedString(locale: Locale = Locale.getDefault()): String {
val nf = NumberFormat.getInstance(locale)
return nf.format(this)
2017-09-22 09:00:12 +02:00
}
val Int.nextPowerOf2: Int
get() {
var n = this
2020-06-08 23:07:20 +02:00
if (n <= 0 || n > 1 shl 30) throw IllegalArgumentException("n is invalid: $n")
2017-09-22 09:00:12 +02:00
n -= 1
n = n or (n shr 16)
n = n or (n shr 8)
n = n or (n shr 4)
n = n or (n shr 2)
n = n or (n shr 1)
return n + 1
}