java n位数,在Java中显示数字的前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!

解决方案

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));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值