Suppose you code a simple divide program in Java and run it. Now suppose it gives you this answer 451.12531 . But you want to select only a single or two digit from this answer may be before the point or after it. In this case we assume that we need to select. Second number which is 5. And you want to print this only. How do you do that?
Asked
Active
Viewed 1,102 times
-3
-
1Does this answer your question? [Double decimal formatting in Java](https://stackoverflow.com/questions/12806278/double-decimal-formatting-in-java) – Steyrix Jul 20 '20 at 11:52
-
It also might be best if you used `BigDecimal` since precision of floating point types is limited. – Nicolas Jul 20 '20 at 11:52
-
`Float.toString(451.12531).charAt(1)` might be one way of doing this. – Ken Y-N Jul 20 '20 at 11:53
3 Answers
1
This can be done by converting your Double to a String using:
String s = String.valueOf(double);
You can then use the Character.getNumericValue()
method to get the desired number/position:
int x = Character.getNumericValue(s.charAt(1));
Full example:
Double d = 451.12531;
String s = String.valueOf(d);
int x = Character.getNumericValue(s.charAt(1));
where x
is your desired number, in the above example it will be 5

Oozeerally
- 842
- 12
- 24
-
Hi What if i want to select all before point or all after point? In this case 451 before point. How do you tell Java to select that. Because we don't know there may be any number before or after point. – CODAR747 Jul 21 '20 at 02:50
-
1@user13926345 take a look at the substring() method: https://beginnersbook.com/2013/12/java-string-substring-method-example/ – Oozeerally Jul 21 '20 at 09:26
-
Can you please help me with this? I tried to select digits after decimla point using Bigdecimal. But it's not working. I have tried this `String getAcreIntoString = new BigDecimal(String.valueOf(acre)).toString(); String getAcreDigit = getAcreIntoString.substring( getAcreIntoString.indexOf('.'), getAcreIntoString.length());` – CODAR747 Jul 21 '20 at 10:17
1
Try this :
private void selectSingleDigit(double number) {
String noInStringFormat = String.valueOf(number);
int digit = getDigitAtSpecificDigit(2,noInStringFormat);
System.out.println(digit);
}
private int getDigitAtSpecificDigit(int index,String str){
if (str != null && !str.isEmpty()) {
return Integer.parseInt(String.valueOf(str.charAt(index)));
} else return -1;
}

chand mohd
- 2,363
- 1
- 14
- 27
-
Can you please help me with this? I tried to select digits after decimla point using Bigdecimal. But it's not working. I have tried this `String getAcreIntoString = new BigDecimal(String.valueOf(acre)).toString(); String getAcreDigit = getAcreIntoString.substring( getAcreIntoString.indexOf('.'), getAcreIntoString.length());` – CODAR747 Jul 21 '20 at 10:17
0
Try using this, here d1 will have digits before decimal point and d2 will have digits after decimal point.
String d1 = text.substring( 0,text.indexOf('.'))
String d2 = text.substring( text.indexOf('.'), text.length());