在Java中显示数字的前n位

发布于 2024-11-25 07:53:26 字数 292 浏览 4 评论 0原文

当用户确定“n”时,我很难创建一种显示数字前 n 位的方法。

例如,用户输入整数“1234567”和若干位数以显示“3”。然后该方法输出“123”。

我有一个想法如何显示第一个数字:

long number = 52345678;
long prefix = number /= (int) (Math.pow(10.0, Math.floor(Math.log10(number))));

但我似乎无法弄清楚如何显示用户定义的前 n 位数字。

谢谢你!

I am having difficulty of creating a method to display first n digits of a number when 'n' is determined by the user.

For example, user inputs an integer '1234567' and a number of digits to display '3'. The method then outputs '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.

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

り繁华旳梦境 2024-12-02 07:53:26
int a = 12345;
int n = 3;
System.out.println((""+a).substring(0, n));

如果你想要一个号码:

int b = Integer.parseInt((""+a).substring(0, n));
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));
禾厶谷欠 2024-12-02 07:53:26

你可以这样做

String num = number + "";
return num.substring(0, numDigits);

如果你需要号码本身,你可以这样做

int div = Math.pow(10, numDigits);
while (number / div > 0)
    number /= 10;

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文