Home > Blockchain >  Java/Kotlin convert numbers into a better string representation ("aa" notation)
Java/Kotlin convert numbers into a better string representation ("aa" notation)

Time:12-27

I am currently programming a point system for players in my app. Since these points can get very large very quickly, I would like to have a system that converts a BigInteger into a better representation (see below).

Examples:

1000 -> 1k
5555555 -> 5.55m
1000000000000000000 -> 1ab

units: k, m, b, t, aa, ab, ac ...

I really doesn't have anything yet, as I don't know where to start. I found this, but it's in C# and I don't really know how to convert it into java/kotlin.

Maybe someone can give me an entry point or just a a code snippet which does that? :D

sorry for the bad english

CodePudding user response:

This is explicitly not a solution, but only a quick attempt to translate the code on gram.gs/gramlog/formatting-big-numbers-aa-notation to Kotlin:

import java.text.DecimalFormat
import kotlin.math.floor
import kotlin.math.log
import kotlin.math.pow

fun formatNumber(value: Double): String {

  val charA = 'a'.code

  val units = mapOf(
    0 to "",
    1 to "K",
    2 to "M",
    3 to "B",
    4 to "T"
  )

  if (value < 1.0) {
    return "0"
  }

  val n = log(value, 1000.0).toInt()
  val m = value / 1000.0.pow(n)
  
  var unit = "";

  if (n < units.count()) {
    unit = units[n]!!
  } else {
    val unitInt = n - units.count()
    val secondUnit = unitInt % 26
    val firstUnit = unitInt / 26
    unit = (firstUnit   charA).toChar().toString()   (secondUnit   charA).toChar().toString()
  }

  return DecimalFormat("#.##").format(floor(m * 100) / 100)   unit

}

println((formatNumber(1.0)))
println((formatNumber(1_000.0)))
println((formatNumber(1_000_000.0)))
println((formatNumber(1_000_000_000.0)))
println((formatNumber(1_000_000_000_000.0)))
println((formatNumber(1_000_000_000_000_000.0)))
println((formatNumber(1_000_000_000_000_000_000.0)))
  • Related