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-04-07 06:12:34 +02:00
|
|
|
fun String?.toLongOr(def: Long): Long {
|
2016-07-30 02:08:57 +02:00
|
|
|
try {
|
2016-12-07 07:15:12 +01:00
|
|
|
return this?.toLong() ?: def
|
2016-07-30 02:08:57 +02:00
|
|
|
} catch (e: NumberFormatException) {
|
|
|
|
return def
|
|
|
|
}
|
2016-08-29 13:03:55 +02:00
|
|
|
}
|
|
|
|
|
2017-04-07 06:12:34 +02:00
|
|
|
fun String?.toIntOr(def: Int): Int {
|
2016-12-03 16:45:13 +01:00
|
|
|
try {
|
2016-12-07 07:15:12 +01:00
|
|
|
return this?.toInt() ?: def
|
2016-12-03 16:45:13 +01:00
|
|
|
} catch (e: NumberFormatException) {
|
|
|
|
return def
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-07 06:12:34 +02:00
|
|
|
fun String?.toDoubleOr(def: Double): Double {
|
2016-08-29 13:03:55 +02:00
|
|
|
try {
|
2017-01-23 14:31:14 +01:00
|
|
|
return this?.toDouble() ?: def
|
2016-08-29 13:03:55 +02:00
|
|
|
} catch (e: NumberFormatException) {
|
2017-01-23 14:31:14 +01:00
|
|
|
return def
|
2016-08-29 13:03:55 +02:00
|
|
|
}
|
2017-01-31 05:04:36 +01:00
|
|
|
}
|
|
|
|
|
2017-03-10 09:37:35 +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)
|
2017-03-03 15:56:29 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 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)
|
|
|
|
}
|