Kotlin extension functions for Numbers

A collection of Kotlin extension methods that simplify many common tasks related to numbers and maths.

fun Double.round(decimals: Int = 2): String = "%.${decimals}f".format(this)

fun Int.leadingZero(): String =
    if (this >= 10) this.toString() else "0$this"

/**
 * The modulus is different from the remainder, and they behave differently for negative numbers.
 */
fun Int.modulus(size: Int) = (((this % size) + size) % size)

Conversions

/**
 * Converts a number of bytes to a pretty value with a unit, all the way up to yottabytes.
 * Supports Standard Internationale (1000 bytes per kB) and 'Kibibytes' conversion (1024 bytes).
 * The unit names are adjusted to match the chosen conversion, e.g.: kilobytes are 'kB'
 * (lowercase k) and kibibytes are 'KiB' (uppercase K, and an i).
 */
fun Long.toMemorySize(si: Boolean = true): String {
    val unit = if (si) 1000 else 1024
    if (this < unit) return "$this B"
    val exp = (Math.log(this.toDouble()) / Math.log(unit.toDouble())).toInt()
    val pre = (if (si) "kMGTPE" else "KMGTPE")[exp - 1] + if (si) "" else "i"
    return String.format("%.1f %sB", this / Math.pow(unit.toDouble(), exp.toDouble()), pre)
}

Date/time conversions


fun Int.secondsToMillis(): Long = this * 1000L
fun Int.minutesToMillis(): Long = this * 60 * 1000L
fun Int.hoursToMillis(): Long = this * 3600 * 1000L
fun Int.daysToMillis(): Long = this * 24 * 3600 * 1000L
fun Int.weeksToMillis(): Long = this * 7 * 24 * 3600 * 1000L
fun Int.monthsToMillis(): Long = (this * 30.5 * 7 * 24 * 3600 * 1000).roundToLong()
fun Int.yearsToMillis(): Long = this * 365 * 24 * 3600 * 1000L

fun Long.millisToMinutes(): Long = this / (60 * 1000L)
fun Long.millisToHours(): Long = this / (60 * 60 * 1000L)
fun Long.millisToDays(): Long = this / (24 * 60 * 60 * 1000L)
fun Long.millisToWeeks(): Long = (this / (7 * 24 * 60 * 60 * 1000.0)).roundToLong()
fun Long.millisToMonths(): Long = (this / (30.5 * 24 * 60 * 60 * 1000.0)).roundToLong()
fun Long.millisToYears(): Long = (this / (365 * 24 * 60 * 60 * 1000.0)).roundToLong()

fun Long.millisToRemainingMinutes(): Int {
    val m = TimeUnit.MILLISECONDS.toMinutes(this) % TimeUnit.HOURS.toMinutes(1)
    return m.toInt()
}

fun Long.millisToRemainingSeconds(): Int {
    val s = TimeUnit.MILLISECONDS.toSeconds(this) % TimeUnit.MINUTES.toSeconds(1)
    return s.toInt()
}
val Int.dp: Int
    get() = (this / Resources.getSystem().displayMetrics.density).toInt()

val Int.px: Int
    get() = (this * Resources.getSystem().displayMetrics.density).toInt()

fun Int.dpToPixels(displayMetrics: DisplayMetrics?): Int {
    if (displayMetrics?.density != null) {
        return this * displayMetrics.density.toInt()
    }
    return this * 2
}

fun Context.convertDpToPx(dp: Float): Float {
    return TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        dp,
        this.resources.displayMetrics
    )
}