Skip to content
Advertisement

How to declare a numerical variable in java that is to hold a digit value with a fixed length of 3 digits always.

How to declare a numerical variable in Java that is to hold a digit value with a fixed length of 3 digits always. That is if i input 0, it should be formated to 000, if i input 31 then it should be formated to 032 and if i input 100 then it should remain 100. I need this for receiving and storing three digit integer value that is sent via rest response as error codes. I tried the normal int and Integer but the preceeding zeros are always removed. Thanks for the help.

Answer

It’s not a property of a numerical variable, but a way of formatting it (of converting it to a string).

It can be done with: String.format("%03d", x) (x being a numerical variable).

Advertisement