import kotlin.math.abs
/**
* 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.
* @throws IllegalArgumentException If position is less than 1.
*/
fun getNthDecimalDigit(value: Double, position: Int): Int {
require(position > 0) {
"Position must be a positive integer."
}
// Convert to a positive value.
val positiveValue = abs(value)
// Convert the number to a string with fixed precision.
val numberString = String.format("%.15f", positiveValue)
// 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
}
return numberString[digitIndex].digitToInt()
}
fun main() {
val number = 123.456789
println("Number: $number")
println()
for (position in 1..6) {
println(
"$position digit after decimal = " +
getNthDecimalDigit(number, position)
)
}
println()
println("Additional Examples")
println("-------------------")
println(
"123.456789, position 4 -> " +
getNthDecimalDigit(123.456789, 4)
)
println(
"-98.7654, position 2 -> " +
getNthDecimalDigit(-98.7654, 2)
)
println(
"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
*/