Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java display length of int containing leading zeros

Tags:

java

I want to display the length of a 4-digit number displayed by the user, the problem that I'm running into is that whenever I read the length of a number that is 4-digits long but has trailing zeros the length comes to the number of digits minus the zeros.

Here is what I tried:

//length of values from number input
int number = 0123;
int length = (int)Math.log10(number) + 1;

This returns to length of 3 The other thing I tried was:

int number = 0123;
int length = String.valueOf(number).length();

This also returned a length of 3.

Are there any alternatives to how I can obtain this length?

like image 721
chino49152 Avatar asked Nov 06 '25 05:11

chino49152


2 Answers

Because int number = 0123 is the equivalent of int number = 83 as 0123 is an octal constant. Thanks to @DavidConrad and @DrewKennedy for the octal precision.

Instead declare it as a String if you want to keep the leading 0

String number = "0123";
int length = number.length();

And then when you need the number, simply do Integer.parseInt(number)


Why is the syntax of octal notation in java 0xx ?

Java syntax was designed to be close to that of C, see eg page 20 at How The JVM Spec Came To Be keynote from the JVM Languages Summit 2008 by James Gosling (20_Gosling_keynote.pdf):

In turn, this is the way how octal constants are defined in C language:

If an integer constant begins with 0x or 0X, it is hexadecimal. If it begins with the digit 0, it is octal. Otherwise, it is assumed to be decimal...

Note that this part is a C&P of @gnat answer on programmers.stackexchange.

https://softwareengineering.stackexchange.com/questions/221797/reasoning-behind-the-syntax-of-octal-notation-in-java

like image 74
Jean-François Savard Avatar answered Nov 08 '25 19:11

Jean-François Savard


Use a string instead:

String number = "0123";
int length = number.length(); // equals 4
like image 26
Sizik Avatar answered Nov 08 '25 18:11

Sizik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!