java 用Java显示数字的前n位数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6757708/
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
Display first n digits of a number in Java
提问by notrockstar
I am having difficulty of creating a method to display first n digits of a number when 'n' is determined by the user.
当用户确定“n”时,我很难创建一种方法来显示数字的前 n 位数字。
For example, user inputs an integer '1234567' and a number of digits to display '3'. The method then outputs '123'.
例如,用户输入一个整数“1234567”和一些数字来显示“3”。该方法然后输出'123'。
I have an idea how to display the first digit:
我有一个想法如何显示第一个数字:
long number = 52345678;
long prefix = number /= (int) (Math.pow(10.0, Math.floor(Math.log10(number))));
But I seem not being able to figure out how to display a user defined first n digits.
但我似乎无法弄清楚如何显示用户定义的前 n 位数字。
Thank you!
谢谢!
回答by Petar Ivanov
int a = 12345;
int n = 3;
System.out.println((""+a).substring(0, n));
If you want a number:
如果你想要一个数字:
int b = Integer.parseInt((""+a).substring(0, n));
回答by Jesus Ramos
You could do this
你可以这样做
String num = number + "";
return num.substring(0, numDigits);
If you need the number itself you can do
如果你需要号码本身,你可以做
int div = Math.pow(10, numDigits);
while (number / div > 0)
number /= 10;