Message Boards Message Boards

0
|
10989 Views
|
7 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Specify exact number of digits?

if the output:

Range [1,10]

is: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

how can I get:

{001, 002, 003, 004, 005, 006, 007, 008, 009, 010} ?

with 3, or other, exact number of digits?

tnk's

POSTED BY: Mutatis Mutandis
7 Replies

one way might be

r = Range[1, 10];
AccountingForm[r, 2, NumberPadding -> {"0", ""}]

enter image description here

POSTED BY: Nasser M. Abbasi

It works for numbers 1 or 2 digits, but the reason why I want to get the output with 3-digit is because the output already contains a 3-digit numbers, with your formula the 3-digit numbers become 4-digit …

there is a way to map placeholders, such ###, with my numbers 1, 2 or 3 digits, and replace the empty positions with 0?

POSTED BY: Mutatis Mutandis
Posted 8 years ago

If you mean selectively padding the 1 or 2 digit numbers with leading zeroes, then you can rewrite [what Nasser has suggested]-

Range[1, 105] /.x_ /; IntegerLength[x] < 3 ->AccountingForm[x, 2, NumberPadding -> {"0", ""}]
POSTED BY: Girish Arabale

AccountingForm does not return strings, which is what the OP probably wants:

StringPadLeft[ToString[#], 3, "0"] & /@ Range[1, 10]

StringPadLeft (for string) or PadLeft (for lists) can be used to pad to a fixed number of characters/items.

POSTED BY: Sander Huisman
Posted 8 years ago

If output with Strings is okay, then you can also write-

IntegerString[#, 10, 3] & /@ Range[1, 100]
POSTED BY: Girish Arabale

That is also very nice solution! You can't really do anything with AccountingForm except for display, if you want to export something or concatenate with other words/characters you'll need strings....

POSTED BY: Sander Huisman

Dear @Mutatis Mutandis you do not need to format code as bold font type. There is a proper formatting for code as you can see in many posts on this forum. Please learn about proper posting here: https://wolfr.am/READ-1ST

POSTED BY: Moderation Team
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract