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,690 questions

55,449 answers

573 users

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

2 Answers

0 votes
object DigitCounterString {

  // Counts digits by converting the number to a string.
  // Idiomatic, clear, and safe for everyday Scala code.
  def countDigitsString(value: Int): Int = {
    val text: String = value.toString

    if (text.startsWith("-"))
      text.length - 1
    else
      text.length
  }

  def main(args: Array[String]): Unit = {
    val number: Int = -12345
    val digits: Int = countDigitsString(number)

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


/*
run:

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

*/

 



answered 2 hours ago by avibootz
0 votes
object DigitCounterLog10 {

  // Counts digits using math: floor(log10(n)) + 1
  // Zero must be handled explicitly.
  def countDigitsLog10(value: Int): Int = {
    val num: Int = math.abs(value)

    if (num == 0)
      1
    else
      math.floor(math.log10(num)).toInt + 1
  }

  def main(args: Array[String]): Unit = {
    val number: Int = 987654321
    val digits: Int = countDigitsLog10(number)

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


/*
run:

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

*/

 



answered 2 hours ago by avibootz
...