当用户确定'n'时,我很难创建一种显示数字的前n位数的方法.
例如,用户输入一个整数'1234567'和一些数字来显示'3'.然后该方法输出'123'.
我知道如何显示第一个数字:
long number = 52345678;
long prefix = number /= (int) (Math.pow(10.0, Math.floor(Math.log10(number))));
Run Code Online (Sandbox Code Playgroud)
但我似乎无法弄清楚如何显示用户定义的前n位数字.
谢谢!
Pet*_*nov 14
int a = 12345;
int n = 3;
System.out.println((""+a).substring(0, n));
Run Code Online (Sandbox Code Playgroud)
如果你想要一个数字:
int b = Integer.parseInt((""+a).substring(0, n));
Run Code Online (Sandbox Code Playgroud)