Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Int from changing 012345 to 5349 [duplicate]

Possible Duplicate:
Integer with leading zeroes

The program I am coding requires me to label an item with an inventory number of 012345 and store it in a int variable.

This is a stripped down example of what I am doing:

int test = 012345;
System.out.println(test);

this prints as:

5349

How do I get it to print out as 012345 rather than 5349?

EDIT: I am entering this into the parameter of a constructor for a custom class i am initializing. Then I use a method to return what the current number is, then print it to the terminal window.

like image 429
Matt Grixti Avatar asked Feb 18 '23 12:02

Matt Grixti


1 Answers

You get a wrong number because when you prepend zero to an integer literal, Java interprets the number as an octal (i.e. base-8) constant. If you want to add a leading zero, use

int test = 12345;
System.out.println("0"+test);

You can also use the formated output functionality with the %06d specifier, like this:

System.out.format("%06d", num);

6 means "use six digits"; '0' means "pad with zeros if necessary".

like image 186
Sergey Kalinichenko Avatar answered Feb 21 '23 01:02

Sergey Kalinichenko