Nick
Nick

Reputation: 137

Convert int which start with leading zero to string

I'm trying to convert int's which start with 0 to strings to be stored in a phone directory as the telephone numbers can start with 0.

I've tried -

int num = 0125;
String.format("%04d",num);

and

Integer.toString(num);

and

DecimalFormat df = new DecimalFormat("0000");
df.format(num);

Each time I get the output 0085 rather than 0125.

How do I convert an int with a leading zero to a string in decimal format?

Upvotes: 2

Views: 1635

Answers (3)

Harmlezz
Harmlezz

Reputation: 8078

An int value starting with a zero is considered to be a octal number (having numbers from 0 - 7) similar to hexadecimal numbers. Hence your value:

0125

is equal to: 1 * 82 + 2 * 81 + 5 * 80 == 64 + 16 + 5 == 85

Don't try to represent a phone-number as an int. Instead use a String and validate it using a regex expression. If you combine both, you may as well represent a phone number by its own type like:

public class PhoneNumber {

    private final String number;

    public PhoneNumber(String number) {
        if (number == null || !number.matches("\\d+([-]\\d+)?")) {
            throw new .....
        }
        this.number = number;
    }
}

The regex is just an example matching phone numbers like: 1234 or 0123-45678.

Upvotes: 9

Maroun
Maroun

Reputation: 96016

0125 is actually 85. Why?

Numbers that starts with 0, are octal numbers. So 0125 is:

5*80 + 2*81 + 1*82 = 85

See the JLS - 3.10.1. Integer Literals:

An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.

Upvotes: 1

Nivas
Nivas

Reputation: 18364

A numeric literal that starts with 0 is considered to be Octal (base 8). 125 base 8 is 85 base 10 (decimal).

Also, int i = 09 will throw a compiler error for the same reason.

See 09 is not recognized where as 9 is recognized

Upvotes: 1

Related Questions