I came across a weird requirement from my client. Format an integer with leading zeros with out changing its type like below

1 = 01 and not "01"
2 = 02 and not "02"

I have searched whole google. But didn't found any way to achieve it. It seems to be it is impossible. How ever I am just checking with community does any out of the box solution is available.

Recommended Answers

All 6 Replies

Very unlikely. Do you have a clue as to why he would request that?

commented: Yes. The above specified functionality is part of an object which return hours part of the time. This value should be used for both display purpose and use for some mathematical operations too. If any of the program which uses this object's hours property +0
Member Avatar for stbuchok

Ask why the business requirement is this way, he may not have a good reason, or even know the difference for that matter.

Not as far as I'm aware. but if converted to string it can be converted back to Integer afterwards. Seems an odd requirement though. can't actually see how this would affect a client at all!

This value should be used for both display purpose and use for some mathematical operations too.

Very bad design, and in most cases impossible. You should provide a value for the int, and a different value (formattedValue) for the ones padded with zeroes.

If this is a requirement from your client, EDUCATE him. You should separate business logic from output formatting.

Sounds like a puzzling requirement.
After all, why would the client care what happens inside the program as long as the program works properly?

One suggestion I can make:
if you are inputting integers padded with leading 0s, make sure to specify the radix parameter, otherwise the numbers might be misinterpreted as being in Octal format (or does your client want numbers in Octal format?). For example, integer_input = parseInt(input_number,10);
Once the number is in the program, it can be manipulated however you want, used for mathematical computations, etc.

When you output the number, and you want it padded with leading 0s, then you can use a small routine like the one described at urtrivedi's link above, or write your own similar routine.

To retain the leading 0s inside the program, as the numbers are being used, would be a tricky operation; I don't know if it could even be done, or why. Are you submitting a code block to a client that will work with other code blocks supplied by other people that require the data in this format? Even so, I don't know how you could save an integer variable like, say, 000067 and still have it recognized as an integer instead of a string.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.