Let's take this method:
public static void getDecimalPart(double n) {
int decimales = 0;
// convertimos el valor a string
String decimalPartString = String.valueOf(n);
// comprobamos si contiene punto de decimales
if (decimalPartString.contains(".")) {
// lo partimos y lo ponemos en un array
String[] doubleArray = decimalPartString.split(".");
// calculamos los decimales
decimales = (int) (Double.valueOf(doubleArray[1]) * (Math.pow(10, doubleArray[1].length()-2)));
}
// imprimimos
System.out.println("El numero " + n + " tiene " + decimales + " decimales");
}
It checks if the string contains(".")
and if so it does split(".")
... then... why when I run:
public static void main(String[] args) {
getDecimalPart(1.25698);
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at q1607.Q38239413.getDecimalPart(Q38239413.java:25) at q1607.Q38239413.main(Q38239413.java:14)
Debugging even confuses me even more since the array is totally empty, it does not matter IOOB
to ask for position 1 and that it does not exist, but rather:
doubleArray = []
What am I not seeing or what am I forgetting? , I'm sure it's something totally obvious but I don't see it....
Things I have tried:
- Use comma.
Use the system decimal symbol:
DecimalFormat format=(DecimalFormat) DecimalFormat.getInstance(); DecimalFormatSymbols symbols=format.getDecimalFormatSymbols(); char sep=symbols.getDecimalSeparator();
In the end I have done the different method, but I am still intrigued as to what is happening.
Because in split the string you are passing is a regular expression (regex) and within regular expressions the dot
"."
has a special meaning. If you want to use it as a point you have to escape it"\\."
While the method
contains
doesn't ask for a regex but aString
and so it works as expected.In java it would look something like this:
To expand the answer a bit, in regular expressions the dot is a wildcard, which means that it is used to capture any character. You have more info in RegexOne
As Luiggi Mendoza mentions, the method
split(String regex)
receives as a parameter a string that represents a regular expression. Another alternative method to take the point.
as a separation character you can apply the following:If you put the square brackets around the point, it explicitly takes it as a string separation criterion. I also recommend using the method
toPlainString(double valor)
of the classBigDecimal
, since if the valuedouble
you are trying to split into parts is very large and you convert it directly withString.valueOf(double valor)
, it will give you an exponential value as a result. If you run the above code, it generates the following output: