[英]Getting the Nth digit after the decimal point
How can I get the Nth digit from a decimal number after the decimal point?如何从小数点后的十进制数中获取第 N 位?
For example:例如:
If the decimal number is 64890.1527
, then the 1st digit is 1
2nd digit is 5
, 3rd digit is 2
, and so on.如果十进制数是64890.1527
,那么第一个数字是1
第二个数字是5
,第三个数字是2
,等等。
Getting the Nth Decimal of a Float获取浮点数的第 N 个小数
Here is a trick for getting the Nth decimal place of a float:这是获取浮点数小数点后第 N 位的技巧:
Example例子
Get the third decimal of 0.12438.得到第三位小数 0.12438。 We would expect the answer to be 4.我们希望答案是 4。
How It Works怎么运行的
Multiplying by 10 n gets the decimal you care about into the ones place.乘以 10 n得到你关心的小数到个位。 Casting to an int drops the decimals.转换为 int 会丢弃小数点。 Modulus by 10 drops all but the ones place.模数除以 10 的位置以外的所有位置。
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您可以使用Double
并在其上调用toString
,然后像这样遍历 charArray
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.