问题
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:
If I have a float like this 5.26, how can I say if the 2nd decimal (which is 6) is bigger/smaller than (a certain number) or not?!
I hope that it's clear to understand.
RE-FORMING THE Qs:
If I have a float that have 2 numbers after the decimal point, I want to check if the second number is bigger than "5" -for example- or not?
回答1:
Getting the Nth Decimal of a Float
Here is a trick for getting the Nth decimal place of a float:
- Take the absolute value
- Multiply by 10n
- Cast to an int
- Modulus by 10
Example
Get the third decimal of 0.12438. We would expect the answer to be 4.
- 0.12438
- Take the absolute value
- 0.12438
- Multiply by 103
- 124.38
- Cast to an int
- 124
- Modulus by 10
- 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
回答2:
Not sure if this is the best solution, but...
Make a string of it; Loop through the string; Check what you wanna check.
回答3:
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);
}
}
来源:https://stackoverflow.com/questions/26048153/getting-the-nth-decimal-of-a-float