简体   繁体   English

如何在java中打印给定整数a = 1234的最后两位数字

[英]How to print last two digits of given integer a=1234 in java

If i'm giving values like a=1234, i want to print last two digits 34 only.. can anyone give me solution for this...如果我给出像 a=1234 这样的值,我只想打印最后两位数字 34 .. 谁能给我解决方案...

int a=1234;
System.out.print(a);

number % 100 will result in last 2 digit number % 100将导致最后2位数

See 看到

用户模数100

System.out.print(String.format("%02d", (abs(a)%100)));

You can try this too 你也可以尝试一下

int a=1234;
System.out.print(String.valueOf(a).substring(2));

Out put 出局

34

Assuming this use-case is for visual output only:假设此用例仅用于视觉输出:

Cast the integer to a string and get its last two characters.将整数转换为字符串并获取其最后两个字符。

int b = 1909;
String bStr = String.valueOf(b);
System.out.print(bStr.substring(bStr.length()-2));
    

This works only for integers with at least two digits though.这仅适用于至少有两位数的整数。 So you might want to make sure you won't get a one-digit integer.因此,您可能想确保不会得到一位整数。

Also, feel free to use a constant instead of the magic number 2 .另外,请随意使用常量而不是幻数2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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