import scala.math.abs
object Main {
/**
* Returns the Nth digit after the decimal point.
*
* Examples:
* getNthDecimalDigit(123.456789, 1) == 4
* getNthDecimalDigit(123.456789, 2) == 5
* getNthDecimalDigit(123.456789, 3) == 6
*
* @param value
* The floating-point number to inspect.
* @param position
* The digit position after the decimal point (1-based).
* @return
* The requested digit (0-9), or 0 if it does not exist.
*/
def getNthDecimalDigit(
value: Double,
position: Int
): Int = {
require(
position > 0,
"Position must be a positive integer."
)
// Convert to positive value.
val positiveValue = abs(value)
// Convert the number to a string with fixed precision.
val numberString = f"$positiveValue%.15f"
// Find the decimal point.
val decimalPos = numberString.indexOf('.')
if (decimalPos == -1) {
return 0
}
// Calculate the index of the requested digit.
val digitIndex = decimalPos + position
// Return 0 if the digit does not exist.
if (digitIndex >= numberString.length) {
return 0
}
numberString(digitIndex).asDigit
}
def main(args: Array[String]): Unit = {
val number = 123.456789
println(s"Number: $number")
println()
for (position <- 1 to 6) {
println(
s"$position digit after decimal = " +
getNthDecimalDigit(number, position)
)
}
println()
println("Additional Examples")
println("-------------------")
println(
s"123.456789, position 4 -> " +
getNthDecimalDigit(123.456789, 4)
)
println(
s"-98.7654, position 2 -> " +
getNthDecimalDigit(-98.7654, 2)
)
println(
s"1.2, position 5 -> " +
getNthDecimalDigit(1.2, 5)
)
}
}
/*
run:
Number: 123.456789
1 digit after decimal = 4
2 digit after decimal = 5
3 digit after decimal = 6
4 digit after decimal = 7
5 digit after decimal = 8
6 digit after decimal = 9
Additional Examples
-------------------
123.456789, position 4 -> 7
-98.7654, position 2 -> 6
1.2, position 5 -> 0
*/