Discuss Scratch

cracklestone
New Scratcher
2 posts

How to pad numbers with zeroes in one line?

Hi there, I was wondering if you could pad numbers with zeroes so that they have n digits or a fixed number of digits. I know you could use loops/etc. to do that, but is there a shorter way to?

The code I currently have is:

(join(letter([2]-(length of (x)))of(0))(x))

which correctly pads one zero for 1 digit numbers and none for 2+ digit numbers. (The “letter n of x” block is used so that the extra 0 doesn't appear when n = 0 i.e. “letter 0 of 0” would output nothing.)
UnconstructivePoster
New Scratcher
100+ posts

How to pad numbers with zeroes in one line?

The shortest method I can think of involves a loop. Given the limited selection of blocks Scratch has, I don't think there's a shorter way to accomplish this for a general value n.

set [your string v] to [starting value]
repeat ((n :: #aaaaaa) - (length of (starting value)))
set [your string v] to (join (0) (your string))
cracklestone
New Scratcher
2 posts

How to pad numbers with zeroes in one line?

Ok, thanks
TeoProotTest
Scratcher
14 posts

How to pad numbers with zeroes in one line?

cracklestone wrote:

Hi there, I was wondering if you could pad numbers with zeroes so that they have n digits or a fixed number of digits. I know you could use loops/etc. to do that, but is there a shorter way to?

The code I currently have is:

(join(letter([2]-(length of (x)))of(0))(x))

which correctly pads one zero for 1 digit numbers and none for 2+ digit numbers. (The “letter n of x” block is used so that the extra 0 doesn't appear when n = 0 i.e. “letter 0 of 0” would output nothing.)
yours is better as it can be used in an expression

Last edited by TeoProotTest (Yesterday 14:09:29)

nembence
Scratcher
500+ posts

How to pad numbers with zeroes in one line?

(join (item ((n::grey)-(length of (x))) of [padding v] :: list) (x))
where the k-th item of the list contains k zeroes

Last edited by nembence (Yesterday 19:58:20)

The_Cool_Test_Alt
Scratcher
100+ posts

How to pad numbers with zeroes in one line?

Why is one-line necessary? A run-without-screen refresh block should be just fine if tick code is your concern.

Powered by DjangoBB