LoginSignup
1
0

More than 5 years have passed since last update.

いいねの数などを「K」とか「M」とかで省略する拡張関数

Posted at

Facebookのように「いいね!」の数を1.5Kとか10Mとか省略するための拡張関数を書きました。
ご自由にお使いください。
桁数を変えれば1.5万とかもいけると思います。

Int.kt
package com.ringored.extensions

const val K = 1_000
const val M = 1_000_000
const val B = 1_000_000_000

/*小数点第1位まで表示*/
const val ROUND_DECIMAL = 10

fun Int.toStringKMB():String{
    val numUnit:String
    var num:Double = if(this < 0){-this.toDouble()} else {this.toDouble()}
    when {
        this < K -> {
            numUnit = ""
        }
        this < M -> {
            numUnit = "K"
            num /= K
        }
        this < B -> {
            numUnit = "M"
            num /= M
        }
        else -> {
            numUnit = "B"
            num /= B
        }
    }
    num = ((Math.round(num * ROUND_DECIMAL)).toDouble()/ROUND_DECIMAL)
    return if(num % 1 == 0.0) {
        (Math.round(num) * if(this<0){-1}else{1}).toString() + numUnit
    } else {
        (num * if(this<0){-1}else{1}).toString() + numUnit
    }
}

使い方

Main.kt
val random = (0..10).random()
val magnification  = (0..100000).random()
val test = (random * magnification)
val test2 = (0..100000000).random()

Log.i(LogUtils.TAG,"before:" +test.toString() +" after:"+test.toStringKMB() )
Log.i(LogUtils.TAG,"before:" +test2.toString() +" after:"+test2.toStringKMB() )

出力結果

before:4887362 after:4.9M
before:196512 after:196.5K
before:97485003 after:97.5M
before:0 after:0
before:21898593 after:21.9M
before:67506 after:67.5K
before:54335794 after:54.3M
before:323694 after:323.7K
before:64874733 after:64.9M
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0