Java 如何提取整数的百位数

Java 如何提取整数的百位数,java,numbers,extract,Java,Numbers,Extract,如何提取整型变量的百分位数? 例如,我有一个随机数: int i = 5654217; 我想要代码来提取数字“2” 我试着去做 i/100 这给了我56542 但我找不到只提取最后一个数字的方法 同样,我真的不确定这是提取变量百的最佳方法。模运算符,%有效地为您提供除法的剩余部分 您可以通过获取数字mod 10来获取最后一位数字。试试(i/100)%10 您可以在此处阅读更多关于模运算的内容:请查找下面的代码: package com.shree.test; public clas

如何提取整型变量的百分位数? 例如,我有一个随机数:

int i = 5654217;
我想要代码来提取数字“2”

我试着去做

i/100
这给了我56542

但我找不到只提取最后一个数字的方法


同样,我真的不确定这是提取变量百的最佳方法。

模运算符,
%
有效地为您提供除法的剩余部分

您可以通过获取数字mod 10来获取最后一位数字。试试
(i/100)%10


您可以在此处阅读更多关于模运算的内容:

请查找下面的代码:

    package com.shree.test;

public class FindNumber {

    public static int findNumberAt(int location,int inputNumber) {
        int number = 0;

        //number =  (inputNumber % (location*10))/location;    // This also works
        number =  (inputNumber/location)%10; // But as mentioned in other comments and answers, this line is perfect solution 

        return number;

    }

    public static void main(String[] args) {
        System.out.println(findNumberAt(100, 5654217));
    }
}

我不是100%确定你在问什么,所以我将对你的问题进行两次猜测。如果它不能回答你的问题,请随时告诉我,我会帮助你的

1) 将整数(int)除以100,最后两位数消失

double x = (double)i/100.0;
//ints cannot store a decimal
2) 您有一个十进制(双精度)并试图输出数百位数字

public int hundredthsDigit(double x){
    if(x>0.0) return (x/100)%10; 
    //This moves the 100s digit to the 1s digit and removes the other digits by taking mod 10
    return 10-Math.abs(x/100)%10;
    // does practically the same thing, but is a work around as mod doesn't work with negatives in java
}

(i/100)%10
首先将int解析为string(),然后在string()中获取特定字符(数字),然后将该字符转换回int(),这是否回答了您的问题@MarceloFilho这是一种过于复杂和低效的方式,无法解决用户7的建议。根据您的问题和示例,是百分之一百,根据您的标题是百分之一百?这是
余数
运算符。一个数字的模数实际上是不同的,它对于正数来说可能是负数。这对负数不起作用。代码删除不会帮助人们学习。请解释你的答案。