[英]Getting the Nth digit after the decimal point
如何從小數點后的十進制數中獲取第 N 位?
例如:
如果十進制數是64890.1527
,那么第一個數字是1
第二個數字是5
,第三個數字是2
,等等。
獲取浮點數的第 N 個小數
這是獲取浮點數小數點后第 N 位的技巧:
例子
得到第三位小數 0.12438。 我們希望答案是 4。
怎么運行的
乘以 10 n得到你關心的小數到個位。 轉換為 int 會丟棄小數點。 模數除以 10 的位置以外的所有位置。
如果輸入為負,我們取絕對值。
代碼片段
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
不確定這是否是最佳解決方案,但是......
把它做成一串; 遍歷字符串; 檢查你想檢查的。
您可以使用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.