Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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...

int a=1234;
System.out.print(a);
like image 519
Mani Beginner Avatar asked Jan 06 '14 09:01

Mani Beginner


4 Answers

number % 100 will result in last 2 digit

See

  • ideone demo
like image 167
jmj Avatar answered Sep 17 '22 15:09

jmj


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.

like image 37
Johannes Avatar answered Sep 18 '22 15:09

Johannes


User modulo 100

System.out.print(String.format("%02d", (abs(a)%100)));
like image 28
user3162144 Avatar answered Sep 19 '22 15:09

user3162144


You can try this too

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

Out put

34
like image 37
Ruchira Gayan Ranaweera Avatar answered Sep 18 '22 15:09

Ruchira Gayan Ranaweera