How to get each number separately by numbers (floating point numbers) and using int Java
Is there a good way to search the first four numbers of a floating-point number and return each number separately with int []?
Example: float 23,51 becomes an integer array, array [0] = 2, array [1] = 3, array [2] = 5, last array [3] = 1
My code:
public void printNumber(float number){ String string = String.valueOf(number); while(!numbers.isEmpty()){ numbers.remove(0); } for(int i = 0; i < string.length(); i++) { int j = Character.digit(string.charAt(i),10); this.number = new Number(j); numbers.add(this.number); System.out.println("digit: " + j); } }
I should mention that number is a class that returns different pictures only according to the number of constructors, and of course the number itself
Numbers is an ArrayList
Solution
Use fixed - point format to convert float to string, and then traverse its characters one by one, ignoring the decimal point
If the number can also be negative, you need to pay attention to the symbols in the string output:
float v = 23.51F; DecimalFormat df = new DecimalFormat("#"); df.setMaximumFractionDigits(8); char[] d = df.format(v).tocharArray(); int count = 0; for (int i = 0 ; i != d.length ; i++) { if (Character.isDigit(d[i])) { count++; } } int[] res = new int[count]; int pos = 0; for (int i = 0 ; i != d.length ; i++) { if (Character.isDigit(d[i])) { res[pos++] = Character.digit(d[i],10); } }
Demo.
Important: note that floating is inherently imprecise, so you may get a "wandering" number or two For example, your sample build
[2 3 5 1 0 0 0 0 2 3]
Finally, there are 2 and 3