如何在 Java 中获取数字的“位置”(例如,数十、数千等)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9962420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the 'place' of a Number in Java (eg. tens, thousands, etc)
提问by Yuvin Ng
How can I determine the number places of a number and determine the number of a loop to run?
如何确定数字的位数并确定要运行的循环数?
For example, if i have an array int[] a= {123,342,122,333,9909}
and int max = a.getMax()
we get the value 9909. I want to get the number place valueof 9909, which is the thousand-th place.
例如,如果我有一个数组int[] a= {123,342,122,333,9909}
,int max = a.getMax()
我们得到了9909的值。我想得到9909的数字位值,它是千位。
For example...
例如...
(number place value,number of loop to run)
(one,1 time)
(tenth,2 time)
(hundred,3 time)
(thousand,4 time)
(ten thousand,5 time)
(hundred thousand,6 time)
Here is my code, however it fails when it meets a zero between an integer...
这是我的代码,但是当它在整数之间遇到零时它会失败......
public static int getMax(int[] t,int n){
int maximum = t[0]; // first value of the array
int index = 0;
int div=1;
int numSpace=0;
int valueTester=34;
boolean done=false;
for (int i=1; i<n; i++) {
if (t[i] > maximum) {
maximum = t[i]; // maximum
index = i; // comparing index
}
}
while(done==false){
if (valueTester==0){
done=true;
}
else{
valueTester=(maximum / div) % 10;
div=div*10;
numSpace++;
}
}
return numSpace;
}
}
回答by Brian
You can use logarithms.
您可以使用对数。
double[] values = {4, 77, 234, 4563, 13467, 635789};
for(int i = 0; i < values.length; i++)
{
double tenthPower = Math.floor(Math.log10(values[i]));
double place = Math.pow(10, tenthPower);
System.out.println(place);
}
回答by The_Fresher
The following code snippet can be used to get the value of the hundredths element in an integer:
以下代码片段可用于获取整数中百分之一元素的值:
public int place(int i) {
int j=(i/100)%10;
return j;
}
回答by wattostudios
To determine the place of the number, you can convert the integer to a String, and get the length of it.
要确定数字的位置,可以将整数转换为字符串,并获取其长度。
For example...
例如...
int[] a= {123,342,122,333,9909};
int maxNumber = a.getMax(); // will return '9909'
int numberPlace = (new Integer(maxNumber)).toString().length; // will return '4'
Then you need to get an English value for the place, such as...
然后你需要得到这个地方的英文值,比如...
String[] placeNames = new String[]{"zero","ones","tens","hundreds","thousands"};
String placeString = placeNames[numberPlace]; // will return "thousands"
Is this all that you're asking? I'm not sure if I understand the rest of your question
这就是你要问的吗?我不确定我是否理解你的其余问题
回答by Hunter McMillen
int a = 9909;
switch(a)
{
case a < 10:
//ones place
break;
case a < 100:
//hundreds place
break;
//etc.....
}
Hope this helps.
希望这可以帮助。