简体   繁体   中英

Parse a Long number in Java

I want to parse a timestamp, a Long number like 14655**56648041** . I want to create from this Long number two other Long numbers, One with the last four numbers 8041 and the second with 5664 . I can convert the number to String, use substring and then convert it again to Long, but I want to know if there is a cleaner way? I tried using % and / but didn't succeed.

最后4位数字是num % 1E4 ,前四个数字是(num % 1E8 - (num % 1E4)) / 1E4

There is. You can obtain the last four numbers by performing a modulo 10000 on the number:

long last4 = all%10000;

You can furthermore obtain the middle four digits by first dividing by 10000 and the again perform modulo:

long midl4 = (all/10000)%10000;

Or putting it all together:

long all = 1465556648041L;

long last4 = all%10000;
long midl4 = (all/10000)%10000;

System.out.println("all="+all);
System.out.println("last4="+last4);
System.out.println("midl4="+midl4);

jDoodle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM