I was trying to compare between decimals in floats using if statements, but I don\'t know how to do it. I searched a lot but didn\'t get the answer.
For example:
Getting the Nth Decimal of a Float
Here is a trick for getting the Nth decimal place of a float:
Example
Get the third decimal of 0.12438. We would expect the answer to be 4.
How It Works
Multiplying by 10n gets the decimal you care about into the ones place. Casting to an int drops the decimals. Modulus by 10 drops all but the ones place.
We take the absolute value in case the input is negative.
Code Snippet
float num = 0.12438f;
int thirdDecimal = (int)(Math.abs(num) * Math.pow(10,3)) % 10; // Equals 4
int fifthDecimal = (int)(Math.abs(num) * Math.pow(10,4)) % 10; // Equals 3
Not sure if this is the best solution, but...
Make a string of it; Loop through the string; Check what you wanna check.
You can take a Double
and call toString
on it and then iterate over charArray like this
public class TestIndexOf {
public static void main(String[] args) {
Double d = 5.26;
String source = d.toString();
char[] chars = source.toCharArray();
char max = source.charAt(source.length() - 1);
boolean isMax = true;
for (char aChar : chars) {
if (max < aChar) {
max = aChar;
isMax = false;
}
}
System.out.println(max + " is max?" + isMax);
}
}