Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,709 questions

55,473 answers

573 users

How to count the number of digits in an integer with Kotlin

2 Answers

0 votes
fun countDigitsString(value: Int): Int {
    val text: String = value.toString()

    // If negative, ignore the leading '-'
    return if (text.startsWith("-")) {
        text.length - 1
    } else {
        text.length
    }
}

fun main() {
    val number: Int = -12345
    val digits: Int = countDigitsString(number)

    println("Number: $number")
    println("Digit count (String method): $digits")
}


/*
run:

Number: -12345
Digit count (String method): 5

*/

 



answered 1 day ago by avibootz
0 votes
import kotlin.math.abs
import kotlin.math.floor
import kotlin.math.log10

fun countDigitsLog10(value: Int): Int {
    val num: Int = abs(value)

    // Zero must be handled explicitly
    if (num == 0) return 1

    // Use floor(log10(n)) + 1
    return floor(log10(num.toDouble())).toInt() + 1
}

fun main() {
    val number: Int = 987_654_321
    val digits: Int = countDigitsLog10(number)

    println("Number: $number")
    println("Digit count (log10 method): $digits")
}


/*
run:

Number: 987654321
Digit count (log10 method): 9

*/

 



answered 1 day ago by avibootz
...