Click here to Skip to main content
16,018,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to convert String value to Long type but "0" value losing. For example I am converted this value:

"032" --> but it converted only 32

What I have tried:

I saw any example but it was not related to my problem.
Posted
Updated 26-Mar-23 23:37pm

Numeric values do not have (or need) leading zeros. The only time they are necessary is when you want to display or print the number, by the use of format strings. For example "%03d" as follows:
Java
int number = 32;
System.out.printf("%03d%n", number);

The zero ensures that leading zeroes are in the output, and the three tells the formatter to print at least three characters.
 
Share this answer
 
Short answer: you cannot do that, string leading zeroes are definitely lost.

As a workaround (if you badly need it) you could maintain such a piece of information (that is the number of leading zeroes in a separate variable, and use it whenever you need to output the number). Something like
Java
class LongWithLeadingZeroes
{
  public long value;
  public int leading_zeroes;
};
 
Share this answer
 
To add to what Richard and Carlo have said ...
When you convert a string to a number, you aren't just stripping away leading zeros - you also convert the number to a value that the computer can understand: binary, stored in a fixed-size variable which for a Java integer is 32 bits. So your example of "032" is converted and stored internally as:
Binary
00000000000000000000000000100000
And so is "32", and "0000032" because this is a fixed size variable. Although the input string could have between 0 and ∞ leading zeros none of them are significant as a numeric value.


Numbers only acquire leading zeros when they are converted back to a string for presentation, either in a report, to a printer, or directly to the user via his display. Then, you use a formatting code which specifies how many digits the number should display at a minimum, as Richard demonstrated.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900