import java.math.BigDecimal;
/**
* Demonstrates how to get the Nth digit after the decimal point
* of a floating-point number.
*/
public class 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 number to inspect.
* @param position The digit position after the decimal point (1-based).
* @return The requested digit, or 0 if it does not exist.
* @throws IllegalArgumentException if position is less than 1.
*/
public static int getNthDecimalDigit(double value, int position) {
if (position < 1) {
throw new IllegalArgumentException(
"Position must be a positive integer."
);
}
// Convert to a positive value
value = Math.abs(value);
/**
* Convert to a string using BigDecimal to reduce
* scientific notation issues.
*/
String numberStr = BigDecimal.valueOf(value).toPlainString();
int decimalPos = numberStr.indexOf('.');
// No decimal point
if (decimalPos == -1) {
return 0;
}
int digitIndex = decimalPos + position;
// Requested digit does not exist
if (digitIndex >= numberStr.length()) {
return 0;
}
return Character.getNumericValue(numberStr.charAt(digitIndex));
}
public static void main(String[] args) {
double number = 123.456789;
System.out.println("Number: " + number);
System.out.println();
for (int i = 1; i <= 6; i++) {
System.out.printf(
"%d digit after decimal = %d%n",
i,
getNthDecimalDigit(number, i)
);
}
System.out.println();
System.out.println("Additional Examples");
System.out.println("-------------------");
System.out.println(
"123.456789, position 4 -> "
+ getNthDecimalDigit(123.456789, 4)
);
System.out.println(
"-98.7654, position 2 -> "
+ getNthDecimalDigit(-98.7654, 2)
);
System.out.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
*/